条件变量(Condition Variables) 是一种同步机制,用于多线程编程中,允许线程等待某个条件成立后再继续执行。条件变量通常与互斥锁(Mutex)一起使用,以确保线程安全。
条件变量本身没有太多类型上的区分,但在不同的操作系统和库中可能有不同的实现方式。常见的有POSIX线程库中的pthread_cond_t
。
以下是一个简单的使用条件变量的示例,模拟生产者-消费者问题:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_empty = PTHREAD_COND_INITIALIZER;
void* producer(void* arg) {
for (int i = 0; i < 20; ++i) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&cond_full, &mutex);
}
buffer[count++] = i;
printf("Produced: %d\n", i);
pthread_cond_signal(&cond_empty);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* consumer(void* arg) {
for (int i = 0; i < 20; ++i) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&cond_empty, &mutex);
}
int item = buffer[--count];
printf("Consumed: %d\n", item);
pthread_cond_signal(&cond_full);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t prod_thread, cons_thread;
pthread_create(&prod_thread, NULL, producer, NULL);
pthread_create(&cons_thread, NULL, consumer, NULL);
pthread_join(prod_thread, NULL);
pthread_join(cons_thread, NULL);
return 0;
}
问题1:死锁
pthread_cond_wait
之前已经持有互斥锁,并且在等待期间互斥锁会被自动释放。问题2:虚假唤醒
问题3:性能问题
通过合理使用条件变量和互斥锁,可以有效解决多线程编程中的同步问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云