多线程模拟-爸爸放橙子给女儿吃,妈妈放苹果给儿子吃

模拟这个游戏:

有一个空盘子一次只能放入一个水果。爸爸放入一个橙子,只有女儿会拿起来吃。妈妈放入一个苹果,只有儿子会拿起来吃。

依次生成这4个线程,利用信号量来同步这4个线程,利用互斥锁来解决爸爸和妈妈争用空盘子的冲突,防止死锁。

当儿子一共吃过8个苹果时,结束整个游戏。

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/time.h>
#include <math.h>

int order=1;
sem_t empty;
sem_t orange;
sem_t apple;

pthread_mutex_t mutex;

void* dad(void *xxx)
{
	while(1)
	{
		sleep(rand()%5); /* get orange into hands */
		sem_wait( &empty);
		pthread_mutex_lock( &mutex);
		printf("\n<%d>\ndad: put orange\n", order++);
		pthread_mutex_unlock( &mutex);
		sem_post( &orange);
	}
	return;
}

void* mom(void *xxx)
{
	while(1)
	{
		sleep(rand()%5); /* get apple into hands */
		sem_wait( &empty);
		pthread_mutex_lock( &mutex);
		printf("\n<%d>\nmom: put apple\n", order++);
		pthread_mutex_unlock( &mutex);
		sem_post( &apple);
	}
	return;
}

void* son(void *xxx)
{
	int i=0;
	while( ++i < 9)
	{
		sem_wait( &apple);
		printf("son: got apple\n");
		sem_post( &empty);
		sleep(rand()%2);    /* eating */
	}
	return;
}

void* daughter(void *xxx)
{
	while(1)
	{
		sem_wait( &orange);
		printf("daughter: got orange\n");
		sem_post( &empty);
		sleep(rand()%2);    /* eating */
	}
	return;
}

int main()
{
	pthread_t dad_id, mom_id, son_id, daughter_id;

	sem_init(&empty, 0, 1);
	sem_init(&apple, 0, 0);
	sem_init(&orange, 0, 0);
	pthread_mutex_init( &mutex, NULL);
	srand(time(0));

	pthread_create( &dad_id, NULL, dad, NULL);
	pthread_create( &mom_id, NULL, mom, NULL);
	pthread_create( &son_id, NULL, son, NULL);
	pthread_create( &daughter_id, NULL, daughter, NULL);

	pthread_join( son_id, NULL);
	sem_destroy( &empty);
	sem_destroy( &apple);
	sem_destroy( &orange);
	pthread_mutex_destroy( &mutex);

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yilonglucky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值