1:有一个隧道,全长5公里,有2列火车,全长200米,
火车A时速 100公里每小时 火车B时速
50公里每小时 现在要求模拟火车反复通过隧道的场景(不可能2列火车都在隧道内运行)
#include <myhead.h>
#include <pthread.h>
// 1:有一个隧道,全长5公里,有2列火车,全长200米,
// 火车A时速 100公里每小时 火车B时速
// 50公里每小时 现在要求模拟火车反复通过隧道的场景(不可能2列火车都在隧道内运行)
pthread_mutex_t mutex;
double len = 5200;
void *trainA(void *arg)
{
while (1)
{
double time = 0;
pthread_mutex_unlock(&mutex);
printf("A出隧道\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *trainB(void *arg)
{ // 50公里每小时
while (1)
{
double time = 0;
pthread_mutex_lock(&mutex);
printf("B出隧道\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *trainC(void *arg)
{
while (1)
{
double time = 0;
pthread_mutex_lock(&mutex);
printf("C出隧道\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&mutex, 0);
sem_t sem;
pthread_t id1;
pthread_t id2;
pthread_t id3;
if (pthread_create(&id1, 0, trainA, 0) != 0)
{
perror("pthread_create_1");
return 1;
}
if (pthread_create(&id2, 0, trainB, 0) != 0)
{
perror("pthread_create_2");
return 2;
}
if (pthread_create(&id3, 0, trainC, 0) != 0)
{
perror("pthread_create_3");
return 3;
}
while (1)
;
pthread_detach(id1);
pthread_detach(id2);
pthread_detach(id3);
pthread_mutex_destroy(&mutex);
return 0;
}
ubuntu@ubuntu:~/zhang/io/i/day6$ ./a.out
A出隧道
B出隧道
C出隧道
A出隧道
C出隧道
B出隧道
A出隧道
C出隧道
B出隧道
A出隧道
C出隧道
B出隧道
^C
#include <myhead.h>
#include <pthread.h>
// 2:有一个隧道,全长5公里,有3列火车,全长200米,
// 火车A时速 100公里每小时 火车B时速 50公里每小时 火车c时速 25公里每小时
// 现在要求 火车A先通过隧道,火车B再通过隧道,最后火车C通过隧道
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
pthread_mutex_t mutex3;
pthread_cond_t cond;
void *trainA(void *arg)
{
double time = 0;
printf("A进入隧道\n");
time = 5000 / (100000 / 60);
printf("用时%lf分钟\n", time);
pthread_mutex_unlock(&mutex2);
}
void *trainB(void *arg)
{ // 50公里每小时
double time = 0;
pthread_mutex_lock(&mutex2);
printf("B出隧道\n");
time = 5000 / (50000 / 60);
printf("用时%lf分钟\n", time);
pthread_mutex_unlock(&mutex3);
}
void *trainC(void *arg)
{
double time = 0;
pthread_mutex_lock(&mutex3);
printf("C出隧道\n");
time = 5000 / (25000 / 60);
printf("用时%lf分钟\n", time);
pthread_mutex_unlock(&mutex3);
}
int main(int argc, const char *argv[])
{
// pthread_cond_init(&cond, 0);
// pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
pthread_mutex_init(&mutex3, 0);
sem_t sem;
pthread_t id1;
pthread_t id2;
pthread_t id3;
if (pthread_create(&id1, 0, trainA, 0) != 0)
{
perror("pthread_create_1");
return 1;
}
if (pthread_create(&id2, 0, trainB, 0) != 0)
{
perror("pthread_create_2");
return 2;
}
if (pthread_create(&id3, 0, trainC, 0) != 0)
{
perror("pthread_create_3");
return 3;
}
pthread_join(id1, 0);
pthread_join(id2, 0);
pthread_join(id3, 0);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
pthread_mutex_destroy(&mutex3);
return 0;
}
ubuntu@ubuntu:~/zhang/io/i/day6$ ./a.out
A进入隧道
用时3.0分钟
B出隧道
用时6.0分钟
C出隧道
用时12.0分钟