跳到内容

useless-with-lock (PLW2101)

源自 Pylint 代码检查工具。

作用

检查在 with 语句中创建并立即丢弃的锁对象。

为什么这不好?

with 语句中创建锁(通过 threading.Lock 或类似方式)无效,因为锁仅在线程之间共享时才相关。

相反,将锁分配给 with 语句之外的变量,并在线程之间共享该变量。

示例

import threading

counter = 0


def increment():
    global counter

    with threading.Lock():
        counter += 1

建议改为

import threading

counter = 0
lock = threading.Lock()


def increment():
    global counter

    with lock:
        counter += 1

参考