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.

66 lines
1.2 KiB

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
sem_t sa,sb,sc;
void* p1(void *arg){
int cnt=0;
for(int i=0;i<30;i++){
sem_wait(&sa);
printf("A\n");
cnt++;
if(cnt%3==0){
sem_post(&sb);
}
else{
sem_post(&sa);
}
}
}
void* p2(void *arg){
int cnt=0;
for(int i=0;i<30;i++){
sem_wait(&sb);
printf("B\n");
cnt++;
if(cnt%3==0){
sem_post(&sc);
}
else{
sem_post(&sb);
}
}
}
void* p3(void *arg){
int cnt=0;
for(int i=0;i<30;i++){
sem_wait(&sc);
printf("C\n");
cnt++;
if(cnt%3==0){
sem_post(&sa);
}
else{
sem_post(&sc);
}
}
}
int main()
{
pthread_t tid[3];
sem_init(&sa,0,1);
sem_init(&sb,0,0);
sem_init(&sc,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");
}