Python Glossary Русский

all Python 3multiprocessingfunction

multiprocessing.Array()

shared memory

Creates a fixed-length ctypes array in shared memory, with a lock by default. It supports indexing and slicing like a list.

Syntax

arr = ctx.Array(typecode_or_type, size_or_initializer, *, lock=True)

The length is fixed for good: there is no append, and out-of-range access raises IndexError. The second argument is either a size (zero-filled) or a sequence of initial values. The slice arr[:] returns a plain list copy, not a view of shared memory. As with Value, the built-in lock does not make arr[i] += 1 atomic; wrap it in with arr.get_lock(). For a byte string use code 'c' and the .value attribute.

Examples

import multiprocessing as mp
def fill(arr):
    for i in range(len(arr)):
        arr[i] = i * i
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    arr = ctx.Array('i', 4)
    p = ctx.Process(target=fill, args=(arr,))
    p.start()
    p.join()
    print(arr[:])  # → [0, 1, 4, 9]
import multiprocessing as mp
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    arr = ctx.Array('i', [1, 2, 3])
    print(len(arr), arr[-1])  # → 3 3
    name = ctx.Array('c', b'abc')
    print(name.value)  # → b'abc'
    try:
        arr[3] = 4
    except IndexError as e:
        print(e)  # → invalid index

See also

Open in the full glossarydocs.python.orgReport an inaccuracy