溫馨提示×

c++ pthread怎么實(shí)現(xiàn)線程間通信

c++
小樊
98
2024-06-25 16:39:31
欄目: 編程語言

在C++中使用pthread庫實(shí)現(xiàn)線程間通信,可以使用互斥鎖(mutex)、條件變量(condition variable)和信號量(semaphore)等同步機(jī)制。以下是使用互斥鎖和條件變量實(shí)現(xiàn)線程間通信的示例代碼:

#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;
}

在上面的示例代碼中,通過互斥鎖保護(hù)共享數(shù)據(jù)shared_data,生產(chǎn)者線程將數(shù)據(jù)寫入shared_data,并發(fā)送信號通知消費(fèi)者線程;消費(fèi)者線程在收到信號后從shared_data中讀取數(shù)據(jù)。通過條件變量實(shí)現(xiàn)線程的等待和通知。

0