有2条隧道,一条快速隧道,一条普通隧道。有5列火车,3列复兴号,2列绿皮扭扭车 要求,复兴号2条隧道都能走,绿皮车只能走普通隧道 模拟火车过隧道的场景
#define _GNU_SOURCE
#include <myhead.h>
pthread_mutex_t quick;
pthread_mutex_t slow;
int qtunnel = 0, stunnel = 0;
typedef struct queue{
char qarr[5] = {0};
char sarr[3] = {0};
qlen = 0;
slen = 0;
}queue;
void *green1(void *agr){
while(1){
if(0 == stunnel){
pthread_mutex_lock(&slow);
stunnel = 1;
printf("K1 in stunnel\n");
usleep(3);
printf("K1 out stunnel\n");
stunnel = 0;
pthread_mutex_unlock(&slow);
}
}
}
void *green2(void *agr){
while(1){
if(0 == stunnel){
pthread_mutex_lock(&slow);
stunnel = 1;
printf("K2 in stunnel\n");
usleep(3);
printf("K2 out stunnel\n");
stunnel = 0;
pthread_mutex_unlock(&slow);
}
}
}
void *bullet1(void *agr){
while(1){
if(0 == qtunnel){
pthread_mutex_lock(&quick);
qtunnel = 1;
printf("G1 in qtunnel\n");
usleep(1);
printf("G1 out qtunnel\n");
qtunnel = 0;
pthread_mutex_unlock(&quick);
continue;
}else if(0 == stunnel){
pthread_mutex_lock(&slow);
stunnel = 1;
printf("G1 in stunnel\n");
usleep(1);
printf("G1 out stunnel\n");
stunnel = 0;
pthread_mutex_unlock(&slow);
}
}
}
void *bullet2(void *agr){
while(1){
if(0 == qtunnel){
pthread_mutex_lock(&quick);
qtunnel = 1;
printf("G2 in qtunnel\n");
usleep(1);
printf("G2 out qtunnel\n");
qtunnel = 0;
pthread_mutex_unlock(&quick);
continue;
}else if(0 == stunnel){
pthread_mutex_lock(&slow);
stunnel = 1;
printf("G2 in stunnel\n");
usleep(1);
printf("G2 out stunnel\n");
stunnel = 0;
pthread_mutex_unlock(&slow);
}
}
}
void *bullet3(void *agr){
while(1){
if(0 == qtunnel){
pthread_mutex_lock(&quick);
qtunnel = 1;
printf("G3 in qtunnel\n");
usleep(1);
printf("G3 out qtunnel\n");
qtunnel = 0;
pthread_mutex_unlock(&quick);
continue;
}else if(0 == stunnel){
pthread_mutex_lock(&slow);
stunnel = 1;
printf("G3 in stunnel\n");
usleep(1);
printf("G3 out stunnel\n");
stunnel = 0;
pthread_mutex_unlock(&slow);
}
}
}
int main(int argc, const char *argv[])
{
pthread_t G1;
pthread_t G2;
pthread_t G3;
pthread_t K1;
pthread_t K2;
pthread_mutex_init(&quick, 0);
pthread_mutex_init(&slow, 0);
pthread_create(&K1, 0, green1, 0);
pthread_create(&K2, 0, green2, 0);
pthread_create(&G1, 0, bullet1, 0);
pthread_create(&G2, 0, bullet2, 0);
pthread_create(&G3, 0, bullet3, 0);
pthread_detach(G1);
pthread_detach(G2);
pthread_detach(G3);
pthread_detach(K1);
pthread_detach(K2);
while(1){
printf("slowtunnel : %d\n", stunnel);
printf("quicktunnel: %d\n", qtunnel);
usleep(5);
}
return 0;
}