啥是条件变量用C代码描述
时间: 2023-11-28 19:48:44 浏览: 34
条件变量(Condition Variable)是一种线程间通信的机制,用于在某些条件满足时唤醒等待该条件的线程。在C语言中,可以使用pthread库中的条件变量相关函数来实现条件变量。
以下是一个简单的使用条件变量的C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 初始化条件变量
int count = 0; // 全局计数器
void *thread_func(void *arg) {
pthread_mutex_lock(&mutex); // 加锁
while(count < 10) { // 等待条件满足
pthread_cond_wait(&cond, &mutex);
}
printf("Thread %d: count = %d\n", *(int*)arg, count); // 执行任务
pthread_mutex_unlock(&mutex); // 解锁
return NULL;
}
int main() {
pthread_t threads[2];
int args[2] = {1, 2};
for(int i = 0; i < 2; i++) {
pthread_create(&threads[i], NULL, thread_func, &args[i]); // 创建线程
}
pthread_mutex_lock(&mutex); // 加锁
while(count < 10) { // 修改全局计数器,唤醒等待的线程
count++;
if(count == 5) {
pthread_cond_broadcast(&cond);
}
}
pthread_mutex_unlock(&mutex); // 解锁
for(int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL); // 等待线程结束
}
return 0;
}
```
在该示例中,主线程创建了两个子线程,并通过全局计数器和条件变量实现了线程间的同步。子线程在等待条件满足时调用pthread_cond_wait函数进入阻塞状态,当主线程修改全局计数器并调用pthread_cond_broadcast函数唤醒等待的线程后,子线程才能继续执行任务。注意加锁和解锁的位置,以及条件变量的使用方法。