all Python 3multiprocessingterm
multiprocessing.Lock
synchronization
A lock shared between processes: only one process or thread at a time inside the critical section. It works with with, just like threading.Lock.
Syntax
lock = ctx.Lock(); with lock: ...
Pass the primitive to the child as a Process argument at creation; it cannot go through a Queue or Pool arguments — RuntimeError "should only be shared between processes through inheritance". Differences from threading.Lock: any process may release it, not only the one that acquired it, and release() on an unlocked lock raises ValueError instead of RuntimeError. The first argument of acquire() is named block, not blocking.
Examples
import multiprocessing as mp
def add(total, lock):
for _ in range(100):
with lock:
total.value += 1
if __name__ == '__main__':
ctx = mp.get_context('spawn')
lock = ctx.Lock()
total = ctx.Value('i', 0, lock=False)
ps = [ctx.Process(target=add, args=(total, lock)) for _ in range(2)]
for p in ps:
p.start()
for p in ps:
p.join()
print(total.value) # → 200
import multiprocessing as mp
import pickle
if __name__ == '__main__':
lock = mp.get_context('spawn').Lock()
try:
lock.release()
except ValueError as e:
print(e) # → semaphore or lock released too many times
try:
pickle.dumps(lock)
except RuntimeError as e:
print(e) # → Lock objects should only be shared between processes through inheritance
See also
Open in the full glossarydocs.python.orgReport an inaccuracy