Compare commits

...

3 Commits
master ... 01

@ -4,25 +4,40 @@
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
sem_t p1_A, p2_B, p3_C;
void* p1(void *arg){
for(int i=0;i<10;i++){
printf("A\n");
sem_wait(&p1_A); //应题目要求“A”第一个输出
usleep(1000*1000/2); //等待0.5秒
printf("A\n");
sem_post(&p2_B); //随后跳转到p2
}
}
void* p2(void *arg){
for(int i=0;i<10;i++){
printf("B\n");
sem_wait(&p2_B); //p2开始等待等p1指示完从此执行
usleep(1000*1000/2); //等待0.5秒
printf("B\n");
sem_post(&p3_C); //随后跳转到p3
}
}
void* p3(void *arg){
for(int i=0;i<10;i++){
printf("C\n");
sem_wait(&p3_C); //这里还是等待。。。。。
usleep(1000*1000/2); //等待0.5秒
printf("C\n");
sem_post(&p1_A); //p3执行完继续跳转到p1再继续执行
}
}
}
int main()
{
pthread_t tid[3];
sem_init(&p1_A, 0, 1);//这里第3个参数设为“1”可以理解为第一个执行
sem_init(&p2_B, 0, 0);
sem_init(&p3_C, 0, 0);
pthread_create(&tid[0], NULL, p1, NULL);
pthread_create(&tid[1], NULL, p2, NULL);
pthread_create(&tid[2], NULL, p3, NULL);

Loading…
Cancel
Save