在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中讀取數據。通過條件變量實現線程的等待和通知。