""" The purpose of this file is to demonstrate how one might use a lock to obtain mutual exclusion. """ from threading import Thread, Lock from time import sleep def slowChange(thing): for i in range(len(thing)): value = thing[i] sleep(0.01) # simulate a lot of work here thing[i] = value + i wrong = [0,0,0,0] ts = [Thread(target=slowChange, args=(wrong,)) for _ in range(10)] for t in ts: t.start() for t in ts: t.join() print('wrong:',wrong) def lockedSlowChange(thing, lock): for i in range(len(thing)): with lock: # this block can only be run by one thread at a time value = thing[i] sleep(0.01) # simulate a lot of work here thing[i] = value + i right = [0,0,0,0] lock = Lock() ts = [Thread(target=lockedSlowChange, args=(right,lock)) for _ in range(10)] for t in ts: t.start() for t in ts: t.join() print('right:',right)