如何使用 pthread_cond_wait 函数挂起一个任务:
时间: 2023-10-17 17:12:31 浏览: 56
使用 pthread_cond_wait 函数可以让一个线程等待另一个线程发送信号,通常用于线程间的同步操作。
以下是使用 pthread_cond_wait 函数挂起一个任务的步骤:
1. 定义一个互斥锁 mutex 和一个条件变量 cond。
```
pthread_mutex_t mutex;
pthread_cond_t cond;
```
2. 在需要等待的线程中加锁 mutex。
```
pthread_mutex_lock(&mutex);
```
3. 在等待前,判断是否满足等待条件,如果不满足,就等待条件变量 cond。
```
while (!condition) {
pthread_cond_wait(&cond, &mutex);
}
```
4. 等待条件变量 cond 时,会自动释放 mutex,等待被唤醒后,重新获得 mutex,继续执行下面的代码。
5. 在唤醒等待线程的线程中,需要先加锁 mutex,然后设置满足条件变量 cond,并发送信号通知等待线程。
```
pthread_mutex_lock(&mutex);
condition = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
```
注意事项:
1. 等待条件变量 cond 时需要先加锁 mutex,否则无法保证线程安全。
2. 等待条件变量 cond 时需要使用 while 循环判断条件,而不是 if 语句,因为可能存在虚假唤醒的情况。
3. 使用条件变量 cond 时需要先初始化,可以使用 pthread_cond_init 函数进行初始化。使用完毕后,需要使用 pthread_cond_destroy 函数进行销毁。
示例代码:
```
pthread_mutex_t mutex;
pthread_cond_t cond;
bool condition = false;
void* thread_func1(void* arg) {
pthread_mutex_lock(&mutex);
while (!condition) {
pthread_cond_wait(&cond, &mutex);
}
// do something
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void* thread_func2(void* arg) {
pthread_mutex_lock(&mutex);
condition = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_func1, NULL);
pthread_create(&thread2, NULL, thread_func2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```