在C++中使用pthread库实现线程间通信,可以使用互斥锁(mutex)、条件变量(condition variable)和信号量(semaphore)等同步机制。以下是使用互斥锁和条件变量实现线程间通信的示例代码:
#include <iostream>#include <pthread.h>int shared_data = 0;pthread_mutex_t mutex;pthread_cond_t cond;void* producer(void* arg) { for(int i = 0; i < 5; i++) { pthread_mutex_lock(&mutex); shared_data = i; std::cout << "Produced: " << i << std::endl; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(NULL);}void* consumer(void* arg) { for(int i = 0; i < 5; i++) { pthread_mutex_lock(&mutex); while(shared_data == 0) { pthread_cond_wait(&cond, &mutex); } std::cout << "Consumed: " << shared_data << std::endl; shared_data = 0; pthread_mutex_unlock(&mutex); } pthread_exit(NULL);}int main() { pthread_t producer_thread, consumer_thread; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0;}在上面的示例代码中,通过互斥锁保护共享数据shared_data,生产者线程将数据写入shared_data,并发送信号通知消费者线程;消费者线程在收到信号后从shared_data中读取数据。通过条件变量实现线程的等待和通知。