示例工程 19-threading-gil-multiprocessing
19-threading-gil-multiprocessing/03-race-condition/race_condition.py
"""演示竞态丢失更新与 Lock 修复。"""
from __future__ import annotations
import threading
THREADS = 4
PER_THREAD = 1000
def forced_race(threads: int = THREADS) -> int:
counter = [0]
barrier = threading.Barrier(threads)
def worker() -> None:
value = counter[0]
barrier.wait(timeout=1)
counter[0] = value + 1
workers = [threading.Thread(target=worker) for _ in range(threads)]
for thread in workers:
thread.start()
for thread in workers:
thread.join()
return counter[0]
def locked_count(threads: int = THREADS, per_thread: int = PER_THREAD) -> int:
counter = [0]
lock = threading.Lock()
def worker() -> None:
for _ in range(per_thread):
with lock:
counter[0] += 1
workers = [threading.Thread(target=worker) for _ in range(threads)]
for thread in workers:
thread.start()
for thread in workers:
thread.join()
return counter[0]
def main() -> None:
print(f"expected: {THREADS}")
print(f"unlocked: {forced_race()}")
print(f"locked: {locked_count()}")
if __name__ == "__main__":
main()