在Linux中,使用pthread_create创建线程时,线程同步是一个重要的问题
互斥锁是一种同步机制,用于确保多个线程在访问共享资源时不会发生冲突。可以使用pthread_mutex_lock和pthread_mutex_unlock函数来加锁和解锁互斥锁。
#include <pthread.h>
pthread_mutex_t lock;
void* thread_func(void *arg) {
pthread_mutex_lock(&lock);
// 访问共享资源
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&lock, NULL);
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&lock);
return 0;
}
条件变量是一种同步机制,用于在多个线程之间传递消息。可以使用pthread_cond_wait和pthread_cond_signal函数来等待和发送条件变量信号。
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int ready = 0;
void* thread_func(void *arg) {
pthread_mutex_lock(&lock);
while (ready == 0) {
pthread_cond_wait(&cond, &lock);
}
// 处理数据
ready = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
pthread_mutex_lock(&lock);
ready = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
屏障是一种同步机制,用于确保多个线程在继续执行之前都达到了某个点。可以使用pthread_barrier_wait函数来等待其他线程。
#include <pthread.h>
#define NUM_THREADS 5
pthread_mutex_t lock;
pthread_cond_t cond;
int ready = 0;
int current = 0;
void* thread_func(void *arg) {
pthread_mutex_lock(&lock);
while (current < NUM_THREADS) {
pthread_cond_wait(&cond, &lock);
}
// 处理数据
ready = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t threads[NUM_THREADS];
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&cond, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
pthread_mutex_lock(&lock);
while (current < NUM_THREADS) {
pthread_cond_wait(&cond, &lock);
}
current = 0;
for (int i = 0; i < NUM_THREADS; i++) {
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&lock);
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
这些是线程同步的一些基本方法。在实际应用中,可能需要根据具体需求选择合适的同步机制。