在Linux C编程中,条件变量(Condition Variables)是一种同步机制,用于协调多个线程之间的共享状态。条件变量允许线程等待某个特定条件的成立,从而避免忙等待(busy-waiting),提高系统资源的利用率。
条件变量通常与互斥锁(Mutex)一起使用,以确保线程安全地访问共享资源。线程在检查条件是否满足之前,必须先获得互斥锁。如果条件不满足,线程会释放互斥锁并进入等待状态,直到其他线程改变条件并通知它。
pthread_cond_init()
: 初始化条件变量。pthread_cond_wait()
: 线程等待条件变量,此函数会自动释放互斥锁,并在被唤醒时重新获得互斥锁。pthread_cond_signal()
: 唤醒等待条件变量的一个线程。pthread_cond_broadcast()
: 唤醒等待条件变量的所有线程。pthread_cond_destroy()
: 销毁条件变量。以下是一个简单的生产者-消费者模型的示例代码,使用条件变量和互斥锁:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFER_SIZE 5
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) {
while (1) {
int item = rand() % 100;
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) {
pthread_cond_wait(&cond_full, &mutex);
}
buffer[count++] = item;
printf("Produced: %d
", item);
pthread_cond_signal(&cond_empty);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void* consumer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) {
pthread_cond_wait(&cond_empty, &mutex);
}
int item = buffer[--count];
printf("Consumed: %d
", item);
pthread_cond_signal(&cond_full);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
pthread_cond_wait()
之前已经获得互斥锁,并且在回调函数中正确处理锁的释放和重新获取。pthread_cond_wait()
之后应该再次检查条件是否满足。通过合理使用条件变量和互斥锁,可以有效地解决多线程编程中的同步问题。
领取专属 10元无门槛券
手把手带您无忧上云