操作系统 / 系统课时

条件变量怎样等待状态变化

条件变量怎样等待状态变化

条件变量解决的不是“等多久”,而是“某个共享状态什么时候满足条件”。跨进程生产者与消费者应把互斥锁、条件变量和状态一起放进共享内存,并在循环中检查条件,避免忙等和错误唤醒。

学习目标

  • 理解 pthread_cond_wait() 为什么必须配合互斥锁
  • 配置可跨进程使用的条件变量
  • 用状态谓词组织生产者与消费者的等待和通知

等待的是状态而不是通知次数

条件变量本身不保存“事件次数”。消费者真正关心的是某个状态谓词,例如 ready == 1。如果状态尚未满足,消费者在持有互斥锁时调用 pthread_cond_wait();该函数会原子地释放互斥锁并进入等待,醒来后再重新获取互斥锁。

因此判断条件必须写成 while,不能写成 if。原因包括虚假唤醒、多个等待者竞争,以及收到通知时条件可能已被其他进程改变。

跨进程条件变量协调生产者和消费者的时序

配置并运行跨进程条件变量

下面示例使用一块 POSIX 共享内存承载互斥锁、条件变量、ready 状态和数据。父进程作为消费者先等待;子进程作为生产者写入数据后发出通知。

c
#define _POSIX_C_SOURCE 200809L

#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>

#define SHM_NAME "/ipc_cond_demo"

typedef struct {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int ready;
    int data;
} SharedState;

static void die_pthread(int rc, const char *what) {
    if (rc != 0) {
        errno = rc;
        perror(what);
        exit(EXIT_FAILURE);
    }
}

int main(void) {
    /* mutex、cond 和谓词状态必须位于同一共享映射。 */
    int fd = shm_open(SHM_NAME, O_CREAT | O_EXCL | O_RDWR, 0600);
    if (fd == -1) {
        perror("shm_open");
        return EXIT_FAILURE;
    }

    if (ftruncate(fd, sizeof(SharedState)) == -1) {
        perror("ftruncate");
        return EXIT_FAILURE;
    }

    SharedState *state = mmap(NULL, sizeof(*state),
                              PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (state == MAP_FAILED) {
        perror("mmap");
        return EXIT_FAILURE;
    }
    close(fd);

    /* 两种同步对象都要显式启用 PROCESS_SHARED。 */
    pthread_mutexattr_t mutex_attr;
    pthread_condattr_t cond_attr;
    die_pthread(pthread_mutexattr_init(&mutex_attr),
                "pthread_mutexattr_init");
    die_pthread(pthread_mutexattr_setpshared(
                    &mutex_attr, PTHREAD_PROCESS_SHARED),
                "pthread_mutexattr_setpshared");
    die_pthread(pthread_condattr_init(&cond_attr),
                "pthread_condattr_init");
    die_pthread(pthread_condattr_setpshared(
                    &cond_attr, PTHREAD_PROCESS_SHARED),
                "pthread_condattr_setpshared");

    die_pthread(pthread_mutex_init(&state->mutex, &mutex_attr),
                "pthread_mutex_init");
    die_pthread(pthread_cond_init(&state->cond, &cond_attr),
                "pthread_cond_init");
    pthread_mutexattr_destroy(&mutex_attr);
    pthread_condattr_destroy(&cond_attr);

    state->ready = 0;
    state->data = 0;

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {
        /* 子进程模拟生产者:先改状态,再发通知。 */
        sleep(1);  /* 仅用于让演示稳定地先进入等待,不承担同步职责。 */
        die_pthread(pthread_mutex_lock(&state->mutex),
                    "producer mutex_lock");
        state->data = 42;
        state->ready = 1;
        printf("producer: data=%d\n", state->data);
        fflush(stdout);
        die_pthread(pthread_cond_signal(&state->cond),
                    "pthread_cond_signal");
        die_pthread(pthread_mutex_unlock(&state->mutex),
                    "producer mutex_unlock");
        _exit(EXIT_SUCCESS);
    }

    /* 消费者始终在持锁状态下检查谓词,并用 while 处理唤醒。 */
    die_pthread(pthread_mutex_lock(&state->mutex),
                "consumer mutex_lock");
    while (!state->ready) {
        die_pthread(pthread_cond_wait(&state->cond, &state->mutex),
                    "pthread_cond_wait");
    }
    printf("consumer: data=%d\n", state->data);
    die_pthread(pthread_mutex_unlock(&state->mutex),
                "consumer mutex_unlock");

    waitpid(pid, NULL, 0);
    pthread_cond_destroy(&state->cond);
    pthread_mutex_destroy(&state->mutex);
    munmap(state, sizeof(*state));
    shm_unlink(SHM_NAME);
    return EXIT_SUCCESS;
}

编译并运行:

bash
gcc -std=c11 -Wall -Wextra -O2 -pthread cond_process.c -o cond_process
./cond_process

预期输出:

text
producer: data=42
consumer: data=42

示例中的 sleep(1) 只是为了让演示更容易观察,不应被当作进程同步手段。真正的同步关系来自 ready、互斥锁和条件变量。

signal 与 broadcast 怎么选

只有一个等待者需要继续工作时,可以使用 pthread_cond_signal() 唤醒至少一个等待线程或进程。多个等待者都需要重新检查条件时,使用 pthread_cond_broadcast() 更合适。

无论选择哪一种,修改共享状态和发送通知都应围绕同一个互斥锁设计。常见顺序是:加锁、修改状态、发送通知、解锁。等待方醒来后仍要再次检查谓词,而不是把“收到通知”等同于“条件一定成立”。

避免丢失唤醒和死锁

所谓“丢失唤醒”通常不是条件变量把通知弄丢了,而是程序没有把状态和通知放在同一套互斥规则中。生产者如果先无锁修改状态,消费者再以另一套逻辑检查,就可能出现竞态。

排查时先确认三件事:条件谓词只在持锁状态下读写;pthread_cond_wait() 使用的互斥锁与保护该谓词的锁是同一把;所有进程映射到同一个共享条件变量。满足这些条件后,等待逻辑才是“条件驱动”,而不是依赖时间延迟或轮询碰运气。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

条件变量怎样等待状态变化

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通