pthread_cond_wait 样例代码
时间: 2023-09-08 18:14:12 浏览: 45
以下是一个简单的 pthread_cond_wait 样例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread1(void* arg)
{
printf("thread1 start\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex); // 等待条件变量
printf("thread1 end\n");
pthread_mutex_unlock(&mutex);
return NULL;
}
void* thread2(void* arg)
{
printf("thread2 start\n");
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond); // 发送条件变量
printf("thread2 end\n");
pthread_mutex_unlock(&mutex);
return NULL;
}
int main()
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```
在这个样例代码中,线程 1 和线程 2 同时运行。线程 1 在等待条件变量 cond,而线程 2 在发送条件变量 cond。当线程 2 发送条件变量后,线程 1 才能继续执行。
在线程 1 中,pthread_cond_wait 函数会阻塞线程,并释放 mutex。当线程 2 发送条件变量后,线程 1 才会被唤醒,继续执行。在线程 2 中,pthread_cond_signal 函数会发送条件变量,唤醒等待条件变量的线程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)