add safe thread example

This commit is contained in:
Mia von Steinkirch 2020-03-02 18:42:49 -08:00
parent 33e78657eb
commit e686184be1

View file

@ -0,0 +1,24 @@
import threading
counter = 0
threads = []
lock = threading.Lock()
def count_with_lock():
global counter
for _ in range(100):
with lock:
counter += 1
for _ in range(100):
thread = threading.Thread(target=count_with_lock)
thread.start()
threads.append(thread)
print(counter)