4. 线程间通信:Condition条件变量,Event事件对象,Queue队列的线程安全

聊到多线程,绕不开的一个话题就是——线程之间怎么说话。

我刚开始写多线程程序的时候,总觉得每个线程各干各的,互不干扰就完事了。后来发现根本不是这么回事。线程之间需要协调,需要传递消息,需要互相等待。说白了,没有通信的多线程,就像一群聋哑人各干各的,效率高不到哪去。

今天咱们就聊聊 Python 和 C++ 里最常用的三种线程间通信方式:Condition 条件变量、Event 事件对象、Queue 队列。这三种东西,我在项目里都用过,踩过坑,也总结了一些经验。

核心要点:线程间通信的本质是「同步 + 数据交换」。Condition 适合「条件满足再干活」的场景,Event 适合「一次性通知」的场景,Queue 则是最通用的「生产者-消费者」模式。

线程间通信三种方式 Condition 条件变量 • 等待/通知机制 • 需要与 Lock 配合 • 适合「条件满足再执行」 • 典型:生产者-消费者 Event 事件对象 • 标志位机制 • set() / wait() / clear() • 适合「一次性通知」 • 典型:启动信号、停止信号 Queue 队列 • 线程安全的数据通道 • put() / get() 自动加锁 • 支持阻塞/超时 • 最通用的通信方式 选择建议 • 需要反复等待条件 → Condition • 只需要通知一次 → Event • 需要传递数据 → Queue • 跨语言协同 → 优先考虑 Queue

4.1 Condition 条件变量:等一个「合适」的时机

Condition 条件变量,说白了就是让线程「等一等,等条件满足了再干活」。你想想看,如果两个线程共享一个资源,一个线程往里放数据,另一个线程往外取数据。取数据的线程不能盲目去取,得等放数据的线程说「好了,有数据了」,它才能取。

我在项目中遇到过这样一个场景:一个爬虫程序,一个线程负责下载网页,另一个线程负责解析。解析线程必须等下载线程把数据放到缓冲区里才能工作。用 Condition 就特别合适。

Python 中的 Condition

import threading
import time

# 共享资源
buffer = []
condition = threading.Condition()

class Producer(threading.Thread):
 def run(self):
 global buffer
 for i in range(5):
 with condition:
 buffer.append(f"数据-{i}")
 print(f"生产: 数据-{i}")
 # 通知消费者,有数据了
 condition.notify()
 time.sleep(0.5)

class Consumer(threading.Thread):
 def run(self):
 global buffer
 for _ in range(5):
 with condition:
 # 如果缓冲区为空,就等着
 while not buffer:
 print("消费者: 没数据,等一会儿...")
 condition.wait()
 data = buffer.pop(0)
 print(f"消费: {data}")

p = Producer()
c = Consumer()
c.start()
p.start()
p.join()
c.join()

我的经验:使用 Condition 时,wait() 一定要放在 while 循环里,而不是 if。为什么?因为线程被唤醒后,条件可能又被其他线程改变了。用 while 重新检查一次,更安全。我曾经因为这个 bug 排查了整整一个下午。

C++ 中的 Condition

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <string>

std::queue<std::string> buffer;
std::mutex mtx;
std::condition_variable cv;

void producer() {
 for (int i = 0; i < 5; ++i) {
 std::unique_lock<std::mutex> lock(mtx);
 buffer.push("数据-" + std::to_string(i));
 std::cout << "生产: 数据-" << i << std::endl;
 cv.notify_one();
 std::this_thread::sleep_for(std::chrono::milliseconds(500));
 }
}

void consumer() {
 for (int i = 0; i < 5; ++i) {
 std::unique_lock<std::mutex> lock(mtx);
 cv.wait(lock, []{ return !buffer.empty(); });
 std::string data = buffer.front();
 buffer.pop();
 std::cout << "消费: " << data << std::endl;
 }
}

int main() {
 std::thread p(producer);
 std::thread c(consumer);
 p.join();
 c.join();
 return 0;
}

注意:C++ 的 condition_variable::wait() 第二个参数可以传入一个谓词(lambda),它会自动在 while 循环中检查条件。这比 Python 手动写 while 要优雅一些,但底层原理是一样的。

4.2 Event 事件对象:一个「开关」搞定通知

Event 比 Condition 简单得多。它就是一个标志位,内部维护一个 bool 值。一个线程可以设置它(set),另一个线程可以等待它(wait)。

Event 适合什么场景?我举个例子:你有一个工作线程,需要等主线程说「开始干活」才启动。或者反过来,主线程需要等工作线程说「我干完了」再继续。这种「一次性通知」的场景,用 Event 最合适。

Python 中的 Event

import threading
import time

# 创建事件对象
start_event = threading.Event()
stop_event = threading.Event()

def worker():
 print("工作线程: 等待启动信号...")
 start_event.wait() # 阻塞,直到事件被设置
 print("工作线程: 收到信号,开始干活!")
 
 # 模拟工作
 for i in range(3):
 print(f"工作线程: 正在处理第 {i+1} 项任务")
 time.sleep(1)
 
 print("工作线程: 干完了!")
 stop_event.set() # 通知主线程

# 启动工作线程
t = threading.Thread(target=worker)
t.start()

time.sleep(2)
print("主线程: 发送启动信号")
start_event.set() # 设置事件,工作线程开始执行

# 等待工作线程完成
stop_event.wait()
print("主线程: 工作线程已结束,程序退出")

关键区别:Event 的 wait() 不会自动重置标志位。如果你想让事件重复使用,需要手动调用 clear() 重置。而 Condition 每次 wait() 返回后,都需要重新获取锁并检查条件。

C++ 中的 Event(用 promise/future 模拟)

C++ 标准库没有直接的 Event 类,但可以用 std::promise 和 std::future 模拟。我个人更喜欢这种方式,因为它更现代、更安全。

#include <iostream>
#include <thread>
#include <future>
#include <chrono>

void worker(std::promise<void>& start_promise,
 std::future<void>& stop_future) {
 std::cout << "工作线程: 等待启动信号..." << std::endl;
 start_promise.set_value(); // 通知主线程:我已就绪
 
 stop_future.wait(); // 等待停止信号
 std::cout << "工作线程: 收到停止信号,退出" << std::endl;
}

int main() {
 std::promise<void> start_promise;
 std::promise<void> stop_promise;
 
 auto start_future = start_promise.get_future();
 auto stop_future = stop_promise.get_future();
 
 std::thread t(worker, std::ref(start_promise), std::ref(stop_future));
 
 // 等待工作线程就绪
 start_future.wait();
 std::cout << "主线程: 工作线程已就绪" << std::endl;
 
 std::this_thread::sleep_for(std::chrono::seconds(2));
 std::cout << "主线程: 发送停止信号" << std::endl;
 stop_promise.set_value();
 
 t.join();
 return 0;
}

我的建议:在 C++ 中,如果只是简单的「一次性通知」,用 promise/future 比手写 condition_variable 要简洁得多。但如果你需要「多次通知」或者「广播通知」,还是得用 condition_variable。

4.3 Queue 队列:最安全的「数据通道」

前面两种方式,Condition 和 Event,本质上都是「同步机制」——它们解决的是「什么时候干活」的问题。但很多时候,线程之间需要传递数据本身。这时候就需要 Queue 了。

Queue 内部已经帮你做好了加锁、等待、通知这些脏活累活。你只需要 put() 和 get() 就行了。说白了,它就是「生产者-消费者」模式的标准答案。

Python 中的 Queue

import threading
import queue
import time

# 创建一个线程安全的队列
q = queue.Queue(maxsize=5)

def producer():
 for i in range(10):
 q.put(f"任务-{i}")
 print(f"生产者: 放入 任务-{i}, 队列大小: {q.qsize()}")
 time.sleep(0.3)

def consumer():
 while True:
 task = q.get() # 如果队列为空,会阻塞
 print(f"消费者: 取出 {task}")
 q.task_done() # 通知队列,任务处理完成
 time.sleep(0.5)
 
 # 模拟停止条件(实际项目中用 Event 更合适)
 if task == "任务-9":
 break

p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)
p.start()
c.start()
p.join()
c.join()

Queue 的三种变体:

类型 特点 适用场景
queue.Queue 先进先出(FIFO) 最常用,任务按顺序处理
queue.LifoQueue 后进先出(LIFO) 类似栈,适合需要优先处理最新任务的场景
queue.PriorityQueue 优先级队列 任务有优先级,高优先级先处理

C++ 中的线程安全队列

C++ 标准库没有内置的线程安全队列,但我们可以自己封装一个。嗯,这里要注意,封装的时候一定要小心死锁。

#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <string>

template<typename T>
class ThreadSafeQueue {
private:
 std::queue<T> q;
 mutable std::mutex mtx;
 std::condition_variable cv;
 size_t max_size;
 
public:
 ThreadSafeQueue(size_t max = 0) : max_size(max) {}
 
 void put(const T& item) {
 std::unique_lock<std::mutex> lock(mtx);
 if (max_size > 0) {
 cv.wait(lock, [this]{ return q.size() < max_size; });
 }
 q.push(item);
 cv.notify_one();
 }
 
 T get() {
 std::unique_lock<std::mutex> lock(mtx);
 cv.wait(lock, [this]{ return !q.empty(); });
 T item = q.front();
 q.pop();
 cv.notify_all(); // 通知生产者,队列有空位了
 return item;
 }
 
 size_t size() const {
 std::lock_guard<std::mutex> lock(mtx);
 return q.size();
 }
};

// 使用示例
void producer(ThreadSafeQueue<std::string>& q) {
 for (int i = 0; i < 5; ++i) {
 q.put("任务-" + std::to_string(i));
 std::cout << "生产: 任务-" << i << std::endl;
 }
}

void consumer(ThreadSafeQueue<std::string>& q) {
 for (int i = 0; i < 5; ++i) {
 std::string task = q.get();
 std::cout << "消费: " << task << std::endl;
 }
}

int main() {
 ThreadSafeQueue<std::string> q(3); // 最大容量3
 std::thread p(producer, std::ref(q));
 std::thread c(consumer, std::ref(q));
 p.join();
 c.join();
 return 0;
}

我曾经踩过的坑:在 C++ 中自己封装线程安全队列时,size() 函数一定要加 mutable 关键字,否则在 const 成员函数里无法修改 mutex。另外,notify_all() 和 notify_one() 的选择要谨慎——如果多个生产者等待空位,用 notify_all() 更合适。

4.4 三种方式怎么选?

说了这么多,到底该用哪个?我总结一下我的经验:

  • Condition 条件变量:适合「反复等待某个条件」的场景。比如缓冲区满了就等,空了也等。需要精细控制。
  • Event 事件对象:适合「一次性通知」的场景。比如启动信号、停止信号。简单粗暴,够用就好。
  • Queue 队列:适合「需要传递数据」的场景。如果你既要同步又要传数据,直接用 Queue 准没错。

你想想看,如果只是通知一个线程「可以开始了」,用 Event 就够了,何必上 Condition?反过来,如果生产者消费者需要反复协调,用 Queue 比自己手写 Condition 要安全得多。

最后说一句:在 Python 和 C++ 协同的场景下,我建议优先考虑 Queue。因为跨语言通信时,数据格式的统一比同步机制更重要。用 Queue 传递序列化后的数据(比如 JSON 或 Protobuf),两边都能理解,省心不少。


,