Python Glossary Русский

all Python 3multiprocessingfunction

multiprocessing.Value()

shared memory

Creates a single ctypes value in shared memory, visible to all processes; it is wrapped with a lock by default. Access it through .value.

Syntax

v = ctx.Value(typecode_or_type, *args, lock=True); with v.get_lock(): v.value += 1

The main trap: v.value += 1 is not atomic even with lock=True; the built-in lock guards the read and the write separately, and parallel processes lose increments. A read-modify-write needs with v.get_lock(). The type is a code as in array: 'i' for int, 'd' for double, 'c' for a single byte; overflowing 'i' silently wraps around. lock=False returns a bare ctypes object without get_lock().

Examples

import multiprocessing as mp
def add(v):
    for _ in range(500):
        with v.get_lock():  # без неё += теряет приращения
            v.value += 1
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    v = ctx.Value('i', 0)
    ps = [ctx.Process(target=add, args=(v,)) for _ in range(2)]
    for p in ps:
        p.start()
    for p in ps:
        p.join()
    print(v.value)  # → 1000
import multiprocessing as mp
if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    print(ctx.Value('d', 1.5).value)  # → 1.5
    print(type(ctx.Value('i', 0)).__name__)  # → Synchronized
    print(hasattr(ctx.Value('i', 0, lock=False), 'get_lock'))  # → False
    big = ctx.Value('i', 2**31 - 1)
    big.value += 1
    print(big.value)  # → -2147483648 — переполнение без ошибки

See also

Open in the full glossarydocs.python.orgReport an inaccuracy