1. 2列火车
#include<myhead.h>pthread_mutex_t m1;
pthread_mutex_t m2;void* run(void* arg)
{while(1){pthread_mutex_lock(&m1);printf("火车B进入\n");printf("A请等待\n");pthread_mutex_unlock(&m2);sleep(2);}
}int main(int argc, const char *argv[])
{pthread_t id;pthread_create(&id,NULL,run,NULL);pthread_detach(id);pthread_mutex_init(&m1,NULL);pthread_mutex_init(&m2,NULL);pthread_mutex_lock(&m1);while(1){pthread_mutex_lock(&m2);printf("火车A进入\n");printf("B请等待\n");pthread_mutex_unlock(&m1);sleep(1);}return 0;
}
2. 3列火车
#include<myhead.h>pthread_mutex_t m1;
pthread_mutex_t m2;
pthread_mutex_t m3;void* run1(void* arg)
{while(1){pthread_mutex_lock(&m2);printf("火车B进入\n");printf("C请等待\n");pthread_mutex_unlock(&m3);sleep(2);}
}
void* run2(void* arg)
{while(1){pthread_mutex_lock(&m3);printf("火车C进入\n");printf("A请等待\n");pthread_mutex_unlock(&m1);sleep(4);}
}int main(int argc, const char *argv[])
{pthread_t id1;pthread_create(&id1,NULL,run1,NULL);pthread_detach(id1);pthread_t id2;pthread_create(&id2,NULL,run2,NULL);pthread_detach(id2);pthread_mutex_init(&m1,NULL);pthread_mutex_init(&m2,NULL);pthread_mutex_init(&m3,NULL);pthread_mutex_lock(&m3);while(1){pthread_mutex_lock(&m1);printf("火车A进入\n");printf("B请等待\n");pthread_mutex_unlock(&m2);sleep(1);}return 0;
}