|
|
|
|
@ -1,48 +0,0 @@
|
|
|
|
|
#include <stdio.h>
|
|
|
|
|
#include <stdlib.h>
|
|
|
|
|
#include <pthread.h>
|
|
|
|
|
#include <unistd.h>
|
|
|
|
|
#include <sys/types.h>
|
|
|
|
|
#include <semaphore.h>
|
|
|
|
|
|
|
|
|
|
//定义信号量——1
|
|
|
|
|
sem_t p1_A, p2_B, p3_C;
|
|
|
|
|
|
|
|
|
|
void* p1(void *arg){
|
|
|
|
|
for(int i=0;i<10;i++){
|
|
|
|
|
sem_wait(&p1_A); //应题目要求,“A”第一个输出
|
|
|
|
|
printf("A\n");
|
|
|
|
|
sem_post(&p2_B); //随后跳转到p2
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
void* p2(void *arg){
|
|
|
|
|
for(int i=0;i<10;i++){
|
|
|
|
|
sem_wait(&p2_B); //p2开始等待,等p1指示完从此执行
|
|
|
|
|
printf("B\n");
|
|
|
|
|
sem_post(&p3_C); //随后跳转到p3
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
void* p3(void *arg){
|
|
|
|
|
for(int i=0;i<10;i++){
|
|
|
|
|
sem_wait(&p3_C); //这里还是等待。。。。。
|
|
|
|
|
printf("C\n");
|
|
|
|
|
sem_post(&p1_A); //p3执行完继续跳转到p1再继续执行
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int main()
|
|
|
|
|
{
|
|
|
|
|
pthread_t tid[3];
|
|
|
|
|
|
|
|
|
|
//初始化信号量——1
|
|
|
|
|
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);
|
|
|
|
|
for(int i = 0; i < 3; i++)
|
|
|
|
|
pthread_join(tid[i], NULL);
|
|
|
|
|
printf("main is over\n");
|
|
|
|
|
}
|