问题描述:
思路:
代码:
#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;
}
运行截图