MST

星途 面试题库

面试题:C语言中Linux条件变量广播机制的基本使用

请简述在Linux环境下,使用C语言时条件变量广播机制的基本流程,并写出一个简单示例代码,包含初始化条件变量、等待条件变量、唤醒条件变量等操作。
34.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

条件变量广播机制基本流程

  1. 初始化条件变量:使用pthread_cond_init函数初始化条件变量。
  2. 等待条件变量:线程通过pthread_cond_wait函数等待条件变量被唤醒。在等待过程中,线程会释放它持有的互斥锁,进入睡眠状态,当条件变量被唤醒时,线程会重新获取互斥锁并继续执行。
  3. 唤醒条件变量:其他线程使用pthread_cond_signal(唤醒一个等待线程)或pthread_cond_broadcast(唤醒所有等待线程)函数来唤醒等待在条件变量上的线程。
  4. 销毁条件变量:使用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秒后设置条件并广播条件变量,唤醒等待的线程。