实现说明
活动部件是函数 bump。
for _ in range(times) 承担全部的逐项处理。
使用要点
- 演示输出是带标签的(
expected:、counted :、no lost updates:),每个操作都会留下自己的一行标注。 - 把
bump当作 API:导入它,其余代码可以忽略。
常见问题
复制和运行之间有安装步骤吗?
没有。从复制到运行之间没有别的要做。 全部导入都来自标准库:threading。 文件在加载时定义 bump。
主要签名是 def bump(times: int) -> None
核心语句
def bump(times: int) -> None:
global counter
for _ in range(times):
# with lock makes the whole read-modify-write exclusive, so no collisions
with lock:
counter += 1
代码示例
import threading
target = 40_000
counter = 0
lock = threading.Lock()
def bump(times: int) -> None:
global counter
for _ in range(times):
# with lock makes the whole read-modify-write exclusive, so no collisions
with lock:
counter += 1
threads = [threading.Thread(target=bump, args=(10_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print("expected:", target)
print("counted :", counter)
print("no lost updates:", counter == target)
print("lock free after joins:", not lock.locked())