from threading import Lock, Thread
counter = 0
lock = Lock()
def worker():
global counter
for _ in range(5_000):
with lock:
counter += 1
threads = [Thread(target=worker) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(counter)Кожен increment виконується під тим самим lock, тому compound update не може переплестися з іншим захищеним increment.
Очікуваний результат: 20000.