1:有一个隧道,全长5公里,有2列火车,全长200米, 火车A时速 100公里每小时 火车B时速 50公里每小时 现在要求模拟火车反复通过隧道的场景(不可能2列火车都在隧道内运行)
int Va=100;
int Vb=50;
double T=5.2;
pthread_mutex_t m1;
pthread_mutex_t m2;
void *run(void*arg)
{
while(1)
{
for(int t=0;t>0;t++)
{ pthread_mutex_lock(&m2);
if((Vb*t)>=T)
{break;}
printf("B车通过\n");
sleep(1);
pthread_mutex_unlock(&m1);
}
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&m1,NULL);
pthread_mutex_init(&m2,NULL);
pthread_mutex_lock(&m2);
pthread_t id;
if(pthread_create(&id,NULL,run,NULL)!=0)
{
perror("pthread_create");
return 1;
}
pthread_detach(id);
pthread_mutex_lock(&m1);
while(1)
{
for(int t=0;t>0;t++)
{ pthread_mutex_lock(&m1);
if((Va*t)>=T)
{break;}
printf("A车通过\n");
sleep(1);
pthread_mutex_unlock(&m2);
}
}
return 0;
}
#2:有一个隧道,全长5公里,有3列火车,全长200米, 火车A时速 100公里每小时 火车B时速 50公里每小时 火车c时速 25公里每小时 现在要求 火车A先通过隧道,火车B再通过隧道,最后火车C通过隧道include <myhead.h>
pthread_mutex_t mutex;
sem_t semA;
sem_t semB;
sem_t semC;
void *trainA(void *arg){
while(1){
sem_wait(&semA);
printf("火车A正在通过隧道\n");
sleep(1);
printf("火车A离开隧道\n");
puts("*******************");
sem_post(&semB);
}
}
void *trainB(void *arg){
while(1){
sem_wait(&semB);
printf("火车B正在通过隧道\n");
sleep(2);
printf("火车B离开隧道\n");
puts("*******************");
sem_post(&semC);
}
}
void *trainC(void *arg){
while(1){
sem_wait(&semC);
printf("火车C正在通过隧道\n");
sleep(2);
printf("火车C离开隧道\n");
puts("*******************");
sem_post(&semA);
}
}
int main(int argc, const char *argv[])
{
//无名信号量
sem_init(&semA,0,1);
sem_init(&semB,0,0);
sem_init(&semC,0,0);
//创建火车A、B、C线程
pthread_t tidA,tidB,tidC;
if(pthread_create(&tidA,NULL,trainA,NULL)!=0){
printf("trainA create error\n");
return -1;
}
if(pthread_create(&tidB,NULL,trainB,NULL)!=0){
printf("trainB create error\n");
return -1;
}
if(pthread_create(&tidC,NULL,trainC,NULL)!=0){
printf("trainC create error\n");
return -1;
}
pthread_detach(tidA);
pthread_detach(tidB);
pthread_detach(tidC);
while(1);
return 0;
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_44559978/article/details/137475338