1、两辆火车互斥
#include <allhead.h>
sem_t a;
void* run(void* arg)
{
while(1)
{
sem_wait(&a);
printf("火车B驶入隧道\n");
sleep(1);
printf("火车B驶出隧道\n");
sleep(1);
sem_post(&a);
}
}
int main(int argc, const char *argv[])
{
sem_init(&a,0,1);
pthread_t id;
if(pthread_create(&id,NULL,run,NULL)!=0)
{
perror("create");
return 1;
}
pthread_detach(id);
while(1)
{
sem_wait(&a);
printf("火车A驶入隧道\n");
sleep(1);
printf("火车A驶出隧道\n");
sleep(1);
sem_post(&a);
}
sem_destroy(&a);
return 0;
}
2、三辆火车同步
#include <allhead.h>
sem_t a;
sem_t b;
sem_t c;
void* run1(void* arg)
{
while(1)
{
sem_wait(&a);
printf("火车B驶入隧道\n");
sleep(1);
printf("火车B驶出隧道\n");
sleep(1);
sem_post(&c);
}
}
void* run2(void* arg)
{
while(1)
{
sem_wait(&c);
printf("火车C驶入隧道\n");
sleep(1);
printf("火车C驶出隧道\n");
sleep(1);
sem_post(&b);
}
}
int main(int argc, const char *argv[])
{
sem_init(&a,0,1);
sem_init(&b,0,1);
sem_init(&c,0,0);
sem_wait(&a);
pthread_t id1;
pthread_t id2;
if(pthread_create(&id1,NULL,run1,NULL)!=0)
{
perror("create");
return 1;
}
if(pthread_create(&id2,NULL,run2,NULL)!=0)
{
perror("create");
return 1;
}
pthread_detach(id1);
pthread_detach(id2);
while(1)
{
sem_wait(&b);
printf("火车A驶入隧道\n");
sleep(1);
printf("火车A驶出隧道\n");
sleep(1);
sem_post(&a);
}
sem_destroy(&a);
sem_destroy(&b);
sem_destroy(&c);
return 0;
}