面试题答案
一键面试条件变量广播机制基本流程
- 初始化条件变量:使用
pthread_cond_init
函数初始化条件变量。 - 等待条件变量:线程通过
pthread_cond_wait
函数等待条件变量被唤醒。在等待过程中,线程会释放它持有的互斥锁,进入睡眠状态,当条件变量被唤醒时,线程会重新获取互斥锁并继续执行。 - 唤醒条件变量:其他线程使用
pthread_cond_signal
(唤醒一个等待线程)或pthread_cond_broadcast
(唤醒所有等待线程)函数来唤醒等待在条件变量上的线程。 - 销毁条件变量:使用
pthread_cond_destroy
函数销毁不再使用的条件变量,释放相关资源。
示例代码
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0;
void *thread_function(void *arg) {
pthread_mutex_lock(&mutex);
while (!ready) {
printf("线程等待条件变量...\n");
pthread_cond_wait(&cond, &mutex);
}
printf("线程被唤醒,条件已满足。\n");
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, thread_function, NULL);
sleep(2); // 主线程休眠2秒模拟其他工作
pthread_mutex_lock(&mutex);
ready = 1;
printf("主线程设置条件并广播。\n");
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
上述代码创建了一个线程,该线程等待条件变量cond
被广播。主线程在休眠2秒后设置条件并广播条件变量,唤醒等待的线程。