线程通信是指在多线程编程中,线程之间为了协调工作、共享数据或传递消息而进行的交互。线程通信对于同步线程的执行、数据共享和避免竞争条件非常重要。以下是一些常见的线程通信机制和使用方法:
1. 共享内存
多个线程可以访问同一块内存区域,通过读写这块内存来交换信息。
2. 信号量(Semaphores)
信号量是一种计数器,可以用来控制对共享资源的访问数量。
3. 互斥锁(Mutexes)
互斥锁用于保护共享资源不被多个线程同时访问。
4. 条件变量(Condition Variables)
条件变量允许线程在某些条件不满足时挂起,并在条件满足时被唤醒。
5. 消息队列
线程可以通过消息队列发送和接收消息,实现线程间的通信。
示例代码(C++11)
以下是使用C++11标准库中的线程、互斥锁和条件变量进行线程通信的示例:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx; // 互斥锁
std::condition_variable cv; // 条件变量
bool ready = false; // 通知标志
void print_id(int id) {
for (int i = 0; i < 5; ++i) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, []{
return ready; }); // 等待通知
std::cout << "Thread " << id << std::endl;
}
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; ++i) {
threads[i] = std::thread(print_id, i);
}
{
std::lock_guard<std::mutex> lck(mtx); // 锁定互斥锁
ready = true; // 设置通知标志
}
cv.notify_all(); // 通知所有等待的线程
for (auto& th : threads) {
th.join(); // 等待所有线程完成
}
return 0;
}
在这个例子中,主线程设置一个标志,然后使用条件变量通知所有其他线程开始执行。每个线程在打印之前都会等待这个通知。
示例代码(Python)
Python的threading
模块提供了类似的线程通信机制:
import threading
# 创建一个锁
lock = threading.Lock()
# 创建一个条件变量
condition = threading.Condition(lock)
def print_numbers():
with condition:
for i in range(1, 6):
print(i)
# 唤醒等待的线程
condition.notify_all()
def wait_for_print():
with condition:
condition.wait()
# 创建线程
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=wait_for_print)
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()