溫馨提示×

c++ pthread線程同步怎么做

c++
小樊
86
2024-06-25 16:27:30
欄目: 編程語言

在C++中使用pthread庫來創(chuàng)建線程進行同步,可以使用互斥鎖(mutex),條件變量(condition variable),信號量(semaphore)等機制來實現(xiàn)線程同步。

  1. 互斥鎖(mutex):互斥鎖可以用來保護共享資源,只有當一個線程獲得了互斥鎖之后才能對共享資源進行操作,其他線程需要等待該線程釋放互斥鎖之后才能繼續(xù)執(zhí)行。
#include <pthread.h>

pthread_mutex_t mutex;

void* thread_func(void* arg) {
    pthread_mutex_lock(&mutex);
    // critical section
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&thread, NULL, thread_func, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_join(thread, NULL);
    return 0;
}
  1. 條件變量(condition variable):條件變量可以用來在某個條件滿足時喚醒等待的線程,配合互斥鎖一起使用可以實現(xiàn)線程的等待和喚醒。
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

void* thread_func(void* arg) {
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);
    // do something
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_create(&thread, NULL, thread_func, NULL);
    pthread_cond_signal(&cond);
    pthread_join(thread, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}
  1. 信號量(semaphore):信號量可以用來控制對共享資源的訪問,通過對信號量的操作來進行線程同步。
#include <pthread.h>
#include <semaphore.h>

sem_t semaphore;

void* thread_func(void* arg) {
    sem_wait(&semaphore);
    // do something
    sem_post(&semaphore);
    return NULL;
}

int main() {
    pthread_t thread;
    sem_init(&semaphore, 0, 1);
    pthread_create(&thread, NULL, thread_func, NULL);
    pthread_join(thread, NULL);
    sem_destroy(&semaphore);
    return 0;
}

以上是使用互斥鎖,條件變量和信號量來實現(xiàn)線程同步的示例代碼,根據(jù)具體的需求和場景選擇合適的同步機制來保證線程安全。

0