在C++中使用pthread库来创建线程进行同步,可以使用互斥锁(mutex),条件变量(condition variable),信号量(semaphore)等机制来实现线程同步。
#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;
}
#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;
}
#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;
}
以上是使用互斥锁,条件变量和信号量来实现线程同步的示例代码,根据具体的需求和场景选择合适的同步机制来保证线程安全。