Locks in Python
Guarding shared state so threads don't corrupt it.
import threading
total = 0
lock = threading.Lock()
def add_many(times):
global total
for _ in range(times):
with lock:
total += 1
threads = [threading.Thread(target=add_many, args=(10_000,))
for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
How it works
- Four threads all increment the same
total. with lock:makes each increment atomic.joinwaits for every thread to finish.
Keywords and builtins used here
add_manydefforglobalrangewith
The run, in numbers
- Lines
- 19
- Characters to type
- 269
- Tokens
- 81
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 46 seconds.
Step 2 of 4 in Threads & processes, step 29 of 53 in Pythonic Python.