本文主要是介绍<操作系统> 售票员司机问题(信号量) 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;
}
运行截图
这篇关于<操作系统> 售票员司机问题(信号量) C语言实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!