You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1006 B

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
sem_t pa,pb,pc;
void* p1(void *arg){
for(int i=0;i<10;i++){
sem_wait(&pa);
usleep(1000*1000/2);
printf("A\n");
sem_post(&pb);
}
}
void* p2(void *arg){
for(int i=0;i<10;i++){
sem_wait(&pb);
usleep(1000*1000/2);
printf("B\n");
sem_post(&pc);
}
}
void* p3(void *arg){
for(int i=0;i<10;i++){
sem_wait(&pc);
printf("C\n");
usleep(1000*1000/2);
sem_post(&pa);
}
}
int main()
{
pthread_t tid[3];
sem_init(&pa,0,1);
sem_init(&pb,0,0);
sem_init(&pc,0,0);
pthread_create(&tid[0], NULL, p1, NULL);
pthread_create(&tid[1], NULL, p2, NULL);
pthread_create(&tid[2], NULL, p3, NULL);
for(int i = 0; i < 3; i++)
pthread_join(tid[i], NULL);
printf("main is over\n");
return 0;
}