Fill the blank
Make the shared counter update safe across threads.
import threading
counts: dict[str, int] = {}
lock = threading.Lock()
def hit(key: str) -> None:
with ____:
counts[key] = counts.get(key, 0) + 1
ts = [threading.Thread(target=hit, args=("a",)) for _ in range(50)]
for t in ts:
t.start()
for t in ts:
t.join()
print(counts)Hint 1 of 1
Every thread must use the same lock.
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A lock
Correct. The read, add and write happen while holding the lock.
counts.get(...) + 1 is a read, an add and a write, and another thread can run between them. Every thread has to hold the same shared lock for the whole read-modify-write so updates can't overlap.
Why not the others?
- B
threading.Lock(). A new lock each call protects nothing. - C
counts. A dict isn't a context manager. - D
threading.Event(). Events signal; they don't give mutual exclusion.