在C++中使用pthread库来创建线程进行同步,可以使用互斥锁(mutex),条件变量(condition variable),信号量(semaphore)等机制来实现线程同步。
- 互斥锁(mutex):互斥锁可以用来保护共享资源,只有当一个线程获得了互斥锁之后才能对共享资源进行操作,其他线程需要等待该线程释放互斥锁之后才能继续执行。
#include
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;
}
- 条件变量(condition variable):条件变量可以用来在某个条件满足时唤醒等待的线程,配合互斥锁一起使用可以实现线程的等待和唤醒。
#include
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;
}
- 信号量(semaphore):信号量可以用来控制对共享资源的访问,通过对信号量的操作来进行线程同步。
#include
#include
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;
}
以上是使用互斥锁,条件变量和信号量来实现线程同步的示例代码,根据具体的需求和场景选择合适的同步机制来保证线程安全。