From 48502e99c5497b11a43ac16fced3a478901894e1 Mon Sep 17 00:00:00 2001 From: p5lxz7ehj <3214708329@qq.com> Date: Fri, 15 Apr 2022 18:42:54 +0800 Subject: [PATCH 1/3] =?UTF-8?q?Update=20=E5=AE=9E=E9=AA=8C2.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 实验2.2 | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/实验2.2 b/实验2.2 index 227dd2b..bfc562f 100644 --- a/实验2.2 +++ b/实验2.2 @@ -4,25 +4,40 @@ #include #include #include + +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); -- 2.34.1