pthread_mutex_t m1;
pthread_mutex_t m2;
void* func(void* age){
while(1){
pthread_mutex_lock(&m2);
printf("the trainB use 371s through the tunnel\n");
sleep(0.1);
pthread_mutex_unlock(&m1);
pthread_mutex_unlock(&m2);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&m1,NULL);
pthread_mutex_init(&m2,NULL);
pthread_t id;
if(pthread_create(&id,NULL,func,NULL)!=0){
perror("pthread_create");
return 1;
}
pthread_detach(id);
while(1){
pthread_mutex_lock(&m1);
printf("trainA use 186s through the tunnel\n");
sleep(0.2);
pthread_mutex_unlock(&m1);
pthread_mutex_unlock(&m2);
}
return 0;
}
sem_t sem1;
sem_t sem2;
sem_t sem3;
void* func1(void* arg){
while(1){
sem_wait(&sem2);
printf("train 367\n");
sleep(0.6);
sem_post(&sem3);
}
}
void* func2(void* arg){
while(1){
sem_wait(&sem3);
printf("train 789\n");
sleep(1);
sem_post(&sem1);
}
}
int main(int argc, const char *argv[])
{
pthread_t id1,id2;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
if(pthread_create(&id1,NULL,func1,NULL)!=0){
perror("pthread_create");
return 1;
}
if(pthread_create(&id2,NULL,func2,NULL)!=0){
perror("pthread_create");
return 1;
}
pthread_detach(id1);
pthread_detach(id2);
while(1){
sem_wait(&sem1);
printf("the train run 186\n");
sleep(0.3);
sem_post(&sem2);
}
return 0;
}