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.

51 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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”第一个输出
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++){
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++){
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];
//初始化信号量——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");
}