在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;
}
以上是使用互斥鎖,條件變量和信號量來實現線程同步的示例代碼,根據具體的需求和場景選擇合適的同步機制來保證線程安全。