IO 条件变量习题 以及 无名管道实现父子进程通信

1.2⒉编写一个程序,开启3个线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示,如ABCABC....….依次递推

void* printA(void* arg){
	int i=0;
	while(i<10){
		pthread_mutex_lock(&mutex);
		if(flag!=0){
			pthread_cond_wait(&cond1,&mutex);
		}
		printf("A-%d--%ld\n",i+1,pthread_self());
		flag=1;
		pthread_cond_signal(&cond2);
		i++;
		pthread_mutex_unlock(&mutex);
	}
}

void* printB(void* arg){
	int i=0;
	while(i<10){
		pthread_mutex_lock(&mutex);
		if(flag!=1){
			pthread_cond_wait(&cond2,&mutex);
		}
		printf("B-%d--%ld\n",i+1,pthread_self());
		flag=2;
		pthread_cond_signal(&cond3);
		i++;
		pthread_mutex_unlock(&mutex);
	}
}

void* printC(void* arg){
	int i=0;
	while(i<10){
		pthread_mutex_lock(&mutex);
		if(flag!=2){
			pthread_cond_wait(&cond3,&mutex);
		}
		printf("C-%d--%ld\n",i+1,pthread_self());
		flag=0;
		pthread_cond_signal(&cond1);
		i++;
		pthread_mutex_unlock(&mutex);
	}
}


void ABCprint(){
	pthread_t A;
	pthread_t B;
	pthread_t C;

	if(pthread_create(&A,NULL,printA,NULL)!=0){
		perror("pthread_create");
		return;
	}

	if(pthread_create(&B,NULL,printB,NULL)!=0){
		perror("pthread_create");
		return;
	}

	if(pthread_create(&C,NULL,printC,NULL)!=0){
		perror("pthread_create");
		return;
	}

	pthread_join(A,NULL);
	pthread_join(B,NULL);
	pthread_join(C,NULL);

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond1);
	pthread_cond_destroy(&cond2);
	pthread_cond_destroy(&cond3);
	
}

2.创建父子进程,实现父子进程的通话。 1)父进程先发送一句话给子进程,子进程接收打印。 2)子进程发送与句话给父进程,父进程接收后打印。 3)重复1)2)步骤即可。 4)当父进程或者子进程发送quit后,父子进程均要结束。

void test_pipe(){
	int ptd1[2];
	int ptd2[2];
	int flag=0;
	if(pipe(ptd1)<0){
		perror("pipe");
		return;
	}
	if(pipe(ptd2)<0){
		perror("pipe");
		return;
	}

	pid_t pid=fork();

	if(pid>0){
		char buf[20];
		while(strcmp("quit",buf)!=0){
			
			bzero(buf,sizeof(buf));
			printf("父进程给子进程发消息:\n");
			scanf("%s",buf);
			write(ptd1[1],buf,sizeof(buf));
				
			read(ptd2[0],buf,sizeof(buf));
			printf("父进程接收到消息:%s\n",buf);
		}
	}else if(pid==0){
		char buf[20];
		while(1){
			read(ptd1[0],buf,sizeof(buf));
			if(strcmp("quit",buf)==0){
				break;
			}
			printf("子进程接收到消息:%s\n",buf);
			bzero(buf,sizeof(buf));
			
			printf("子进程给父进程发消息:\n");
			scanf("%s",buf);
			write(ptd2[1],buf,sizeof(buf));
			if(strcmp("quit",buf)==0){
				exit(0);
			}
		}
		write(ptd2[1],"quit",4);
		exit(0);
	}else{
		perror("fork");
		return;
	}

	wait(NULL);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值