国际访客建议访问 Primers 编程伙伴 国际服 以获得更好的体验。 快速访问 Python 线程控制 条件变量

# Python 的条件变量

条件变量(Condition Variable) 是操作系统和并发编程中的一种同步机制,用于线程/进程间的协调通信。 它允许线程在特定条件不满足时主动等待,直到其他线程通知条件可能已发生变化。

在 Python 中使用 threading 模块的 Condition 类创建条件变量,可以通过 wait 方法等待通知,notify 方法发送通知。

条件变量包含一个锁,在创建条件变量时可以通过参数传递这个锁,如果没有则会自动创建一个可重入锁。 可以通过 acquire 方法加锁,release方法解锁,可以使用 with 语句。

下面是一个示例,consumer 线程需要等待 count 变成 10 再继续运行:

from threading import Thread, Condition

count:int = 0
cond = Condition()

def consumer():
    global count

    while True:
        with cond:                  # 加锁保护 count
            print('consumer')

            cond.wait()             # 原子地解锁并阻塞等待通知,收到通知后自动加锁
            if (count == 10):       # 检查 count 的值
                print(count)
                break


def producer():
    global count

    while True:
        with cond:                  # 加锁保护 count
            print('producer')
            count += 1              # count 加一
            cond.notify()           # 发送通知

            if (count == 10):       # 结束
                break

t1 = Thread(target=consumer)        # 创建线程
t2 = Thread(target=producer) 
t1.start()                          # 启动线程
t2.start()
t1.join()                           # 等待线程结束
t2.join()
如果不使用条件变量,而是仅使用锁保护 countconsumer 轮询检查 count 的值。 即使 count 没有发生变化,consumer 仍会调度进入,浪费 CPU 时间。
本文 更新于: 2025-05-31 19:53:12 创建于: 2025-05-31 19:53:12