面试题答案
一键面试条件变量基本概念
在Linux环境下的C语言编程中,条件变量(condition variable)是一种同步机制,用于线程间的通信。它允许线程等待某个特定条件满足,从而避免无效的忙等待,提高程序效率。条件变量通常与互斥锁一起使用,互斥锁用于保护共享资源,而条件变量用于线程间的同步。
代码示例
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 定义互斥锁和条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int condition_met = 0;
// 线程函数1
void* thread_function1(void* arg) {
// 模拟一些工作
sleep(2);
pthread_mutex_lock(&mutex);
condition_met = 1;
printf("线程1设置条件为满足,唤醒等待线程\n");
pthread_cond_signal(&cond); // 唤醒一个等待的线程
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
// 线程函数2
void* thread_function2(void* arg) {
pthread_mutex_lock(&mutex);
while (!condition_met) {
printf("线程2等待条件满足...\n");
pthread_cond_wait(&cond, &mutex); // 等待条件变量,同时释放互斥锁
}
printf("线程2条件已满足,继续执行\n");
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main() {
pthread_t thread1, thread2;
// 创建线程1
if (pthread_create(&thread1, NULL, thread_function1, NULL) != 0) {
perror("pthread_create");
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, thread_function2, NULL) != 0) {
perror("pthread_create");
return 1;
}
// 等待线程结束
if (pthread_join(thread1, NULL) != 0) {
perror("pthread_join");
return 1;
}
if (pthread_join(thread2, NULL) != 0) {
perror("pthread_join");
return 1;
}
// 销毁互斥锁和条件变量
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
上述代码中:
- 初始化:使用
PTHREAD_MUTEX_INITIALIZER
和PTHREAD_COND_INITIALIZER
分别初始化互斥锁和条件变量。 - 等待:
pthread_cond_wait
函数用于等待条件变量,它会自动释放互斥锁并使线程进入睡眠状态,当条件变量被唤醒时,线程会重新获取互斥锁并继续执行。 - 唤醒:
pthread_cond_signal
函数用于唤醒一个等待在条件变量上的线程。如果有多个线程等待,通常唤醒最早等待的线程。还有pthread_cond_broadcast
函数可唤醒所有等待的线程。最后在程序结束时,使用pthread_mutex_destroy
和pthread_cond_destroy
销毁互斥锁和条件变量。