You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用两个Semaphore控制两个线程的执行进度?

解决方案:用两个信号量实现线程同步

要实现两个线程都输出"entered"消息后再执行退出逻辑,核心是让两个线程互相等待对方完成进入通知。我们可以用两个初始值为0的信号量,分别作为两个线程的"已进入"通知信号。

修改后的完整代码

#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>

// 定义全局信号量,供两个线程访问
sem_t sem1;
sem_t sem2;

void *child1(void *arg) {
    printf("child thread 1 entered!\n");
    // 通知child2:我已经完成进入输出
    sem_post(&sem1);
    // 等待child2完成进入输出
    sem_wait(&sem2);

    printf("child thread 1 exits!\n");
    return NULL;
}

void *child2(void *arg) {
    printf("child thread 2: entered!\n");
    // 通知child1:我已经完成进入输出
    sem_post(&sem2);
    // 等待child1完成进入输出
    sem_wait(&sem1);

    printf("child thread 2: exits\n");
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t p1, p2;
    printf("parent thread: begin\n");
    
    // 初始化两个信号量,初始值为0
    sem_init(&sem1, 0, 0);
    sem_init(&sem2, 0, 0);

    pthread_create(&p1, NULL, child1, NULL);
    pthread_create(&p2, NULL, child2, NULL);
    
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);
    
    // 销毁信号量,释放资源
    sem_destroy(&sem1);
    sem_destroy(&sem2);
    
    printf("parent thread: end\n");
    return 0;
}

代码逻辑说明

  • 信号量初始化:sem_init(&sem1, 0, 0) 中第三个参数是初始值,设为0表示初始时没有可用资源。
  • 线程执行流程:
    1. 每个线程先输出"entered"消息,确认自己已经完成进入步骤。
    2. 调用sem_post给自己对应的信号量加1,相当于向对方发送"我已进入"的通知。
    3. 调用sem_wait等待对方的信号量:如果对方还没完成进入输出,当前线程会阻塞;只有当对方执行了sem_post后,当前线程才能继续执行退出逻辑。
  • 这样无论两个线程的启动顺序如何,都必须等到双方都输出了"entered"后,才会进入退出步骤,完全符合需求。

内容的提问来源于stack exchange,提问作者Inu_901

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:40:20