父亲儿子女儿放取水果进程/线程间通信程序设计与实现

父亲儿子女儿放取水果进程/线程间通信程序设计与实现
在这里插入图片描述

代码:
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_t onelock;
pthread_mutex_t twolock;
int mutex=1;//互斥
int count=0;//计数,记录放了多少个水果
int apple=0;//盘中苹果的个数
int orange=0;//盘中桔子的个数
int choice=0;//父亲选择放置桔子还是苹果
int number;//记录应该放置多少个水果
void wait()
{
     //wait操作
	pthread_mutex_lock(&onelock);
	while(mutex<=0);
	mutex=mutex-1;
	pthread_mutex_unlock(&onelock);
}

void signal()
{
     //signal操作
	pthread_mutex_lock(&twolock);
	while(mutex!=0);
	mutex= mutex+1;
	pthread_mutex_unlock(&twolock);
}

void *father()
{
	while(1)
	{
		if(orange==0&&apple==0)
		{
			wait();
			sleep(2);
			if(choice==1)
			{
				orange=1;
				printf("爸爸放置了一个桔子\n");
			}
			if(choice==2)
			{
				apple=1;
				printf("爸爸放置了一个苹果\n");
			}
			choice=0; 
            count++;
			signal();
		}
		if(count==number)
        {
            pthread_exit (NULL);
        }
	}
}
void *son()
{
	while(1)
	{
		if(orange==1)
		{
			wait();
			sleep(2);
			orange=0;
			choice=0; 
			printf("儿子从盘子中拿了一个桔子\n");
			if(count!=number)
			{
			scanf("%d",&choice);
			}
			signal();
		}
        if(count==number&&orange!=1)
        {
            pthread_exit (NULL);
        }
	}
}
void *daughter()
{
	while(1)
	{
		if(apple==1)
		{
			wait();
			sleep(2);
			apple=0;
			choice=0; 
			printf("女儿从盘子中拿了一个苹果\n");
			if(count!=number)
			{
			scanf("%d",&choice);
			}
			signal();
		}
		if(count==number&&apple!=1)
        {
            pthread_exit (NULL);
        }
	}
}

int main()
{
    pthread_mutex_init(&onelock,NULL);
    pthread_mutex_init(&twolock,NULL);
//父亲 女儿 儿子进程
pthread_t fatherThread;
	pthread_t daughterThread;
	pthread_t sonThread;
	
	printf("请输入父亲放置水果的次数:");
	scanf("%d",&number);
	printf("请输入父亲放置的水果是什么,1为桔子,2为苹果: \n");
	scanf("%d",&choice); 

	pthread_create(&fatherThread,NULL,father,NULL);
	pthread_create(&daughterThread,NULL,daughter,NULL);
	pthread_create(&sonThread,NULL,son,NULL);
	pthread_join(fatherThread,NULL);
	pthread_join(daughterThread,NULL);
	pthread_join(sonThread,NULL);
}

运行结果:
在这里插入图片描述

  • 4
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值