<操作系统> 售票员司机问题(信号量) C语言实现

问题描述:
在这里插入图片描述
思路:
在这里插入图片描述

代码:

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

sem_t door,stop;                     //设置关门和停车两个信号量
void *thread_driver(void *arg)      //司机线程
{
        while(1){
        sem_wait(&door);             //P(door),等待关门信号
        printf("启动\n");
        printf("驾驶\n");
        sleep(2);
        printf("到站停车\n");
        sem_post(&stop);              //V(close),发送停车信号
}
}
void *thread_conductor(void *arg)
{
        while(1){
        printf("关门\n");
        sem_post(&door);             //V(door)发送关门信号
        printf("卖票\n");
        sem_wait(&stop);             //P(stop)等待停车信号
        printf("开门\n");
        }
}
int main()
{
        int sg1,sg2;
        pthread_t driver,conductor;
        sg1=sem_init(&door,0,0);
        sg2=sem_init(&stop,0,0);
        pthread_create(&driver,NULL,(void *)thread_driver,NULL);
                pthread_create(&conductor,NULL,(void *)thread_conductor,NULL);
                pthread_join(driver,NULL);
                pthread_join(conductor,NULL);
                return 0;
}
                                                                 

运行截图
在这里插入图片描述

  • 8
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值