条件变量(Condition Variables)是多线程编程中的一个重要概念,主要用于线程间的同步。它允许一个或多个线程等待某个条件成立,而其他线程则在条件满足时通知等待的线程。条件变量通常与互斥锁(Mutex)一起使用,以确保线程安全。
在Linux中,条件变量主要有两种类型:
pthread_cond_t
类型表示。cond_t
类型表示。条件变量广泛应用于以下场景:
以下是一个使用POSIX条件变量的简单示例,展示了生产者-消费者问题的实现:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t mutex;
pthread_cond_t cond_producer;
pthread_cond_t cond_consumer;
void* producer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&cond_producer, &mutex);
}
buffer[count++] = rand() % 100;
printf("Produced: %d\n", buffer[count - 1]);
pthread_cond_signal(&cond_consumer);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* consumer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&cond_consumer, &mutex);
}
int item = buffer[--count];
printf("Consumed: %d\n", item);
pthread_cond_signal(&cond_producer);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond_producer, NULL);
pthread_cond_init(&cond_consumer, NULL);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond_producer);
pthread_cond_destroy(&cond_consumer);
return 0;
}
pthread_cond_wait
之前已经获取了互斥锁,并且在pthread_cond_signal
或pthread_cond_broadcast
之后释放互斥锁。pthread_cond_signal
或pthread_cond_broadcast
,线程也可能从pthread_cond_wait
中醒来。为了避免这种情况,应该在循环中检查条件。pthread_cond_init
进行初始化。通过以上方法,可以有效解决条件变量在Linux多线程编程中常见的问题。
领取专属 10元无门槛券
手把手带您无忧上云