理发师问题-多线程-信号量-互斥访问共享区

不废话,直接上代码

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

#define CHAIRS 5

sem_t customers;
sem_t barbers;
pthread_mutex_t mutex;
int waiting = 0;
int if_no_more = 0;

void* barber(void *xxx)
{
	while(1)
	{
		sem_wait( &customers); /* get a customer */

		pthread_mutex_lock( &mutex);
		printf("barber: Begin to cut! ");
		printf("%d customers waiting now\n", --waiting);
		pthread_mutex_unlock( &mutex);

		//cut_hair();
		sleep(rand()%7 + 1);

		sem_post( &barbers); /* tell this customer job done */

		/* when $if_no_more is true, $waiting is not in shared area */
		if ( if_no_more && 0 == waiting)
			break;
	}

	sleep(3); /* wait for the last customer left */
	printf("barber: offtime, Bye!\n");
	return;
}

void* customer(void *xxx)
{
	int color = rand()%6 + 31;
#define START "\033[1;%dm"
#define END "\033[0m\n"
	pthread_mutex_lock( &mutex);

	if( waiting < CHAIRS)
	{
		printf(START"\t%d customers waiting now including me #%u"END, \
				color, ++waiting, (unsigned int)pthread_self());
		pthread_mutex_unlock( &mutex);

		sem_post( &customers); /* stand in queue */
		sem_wait( &barbers); /* wait for the barber's job */

		printf(START"\tcustomer #%u: Nice job, Bye!"END, color, (unsigned int)pthread_self());
	}
	else
	{
		printf("customer #%u: Too many customers, Bye!\n", (unsigned int)pthread_self);
		pthread_mutex_unlock( &mutex);
	}
	return;
}

int main()
{
	int i;
	pthread_t barber_id, customer_id;

	sem_init(&customers, 0, 0);
	sem_init(&barbers, 0, 0);
	pthread_mutex_init( &mutex, NULL);
	srand(time(0));

	pthread_create( &barber_id, NULL, barber, NULL);

	for(i=0; i<15; i++)
	{
		sleep(rand()%4 + 1);
		pthread_create( &customer_id, NULL, customer, NULL);
	}

	if_no_more = 1; /* tell the barber that no more customers */
	pthread_join( barber_id, NULL);

	sem_destroy( &customers);
	sem_destroy( &barbers);
	pthread_mutex_destroy( &mutex);

	return 0;
}


在来个运行截图


有1个理发师线程,主进程先后生成数个顾客线程。如果有新顾客发现等的人太多就直接离开。成功排队的顾客用彩色显示。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yilonglucky

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

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

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

打赏作者

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

抵扣说明:

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

余额充值