问题描述:
思路:
代码:
#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;
}
运行截图
本文发布于:2024-02-03 04:18:11,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170690509148599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |