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.
60 lines
1.2 KiB
60 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 pa,pb,pc;
|
|
void* p1(void *arg){
|
|
for(int i=0;i<30;i++){
|
|
sem_wait(&pa);
|
|
usleep(1000*1000/2);
|
|
printf("A\n");
|
|
if((i+1)%3==0){
|
|
sem_post(&pb);
|
|
sem_post(&pb);
|
|
sem_post(&pb);
|
|
}
|
|
}
|
|
}
|
|
void* p2(void *arg){
|
|
for(int i=0;i<30;i++){
|
|
sem_wait(&pb);
|
|
usleep(1000*1000/2);
|
|
printf("B\n");
|
|
if((i+1)%3==0){
|
|
sem_post(&pc);
|
|
sem_post(&pc);
|
|
sem_post(&pc);
|
|
}
|
|
}
|
|
}
|
|
void* p3(void *arg){
|
|
for(int i=0;i<30;i++){
|
|
sem_wait(&pc);
|
|
printf("C\n");
|
|
usleep(1000*1000/2);
|
|
if((i+1)%3==0){
|
|
sem_post(&pa);
|
|
sem_post(&pa);
|
|
sem_post(&pa);
|
|
}
|
|
}
|
|
}
|
|
|
|
int main()
|
|
{
|
|
pthread_t tid[3];
|
|
sem_init(&pa,0,3);
|
|
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;
|
|
}
|
|
|