← 中文资源

简体中文版本

threading.Lock 守住共享计数

用 with lock 包住读-改-写整段操作,四个线程各加一万次也不丢更新,计数精确等于四万;退出 with 块时锁自动释放。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

expected: 40000
counted : 40000
no lost updates: True
lock free after joins: True

实现说明

活动部件是函数 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())