操作系统 | 经典同步问题之理发师问题

理发师问题Customer&Barber

· 理发师由等待间(包含N个等待座位)和理发间(一把理发椅)构成。
· 没有顾客时,理发师睡觉;顾客进入理发店发现理发师睡觉则唤醒他,如果座位已满就离开。

下面是该问题的伪代码表述:

const chairs=5;
//一般信号量customers表示顾客的人数
//互斥信号量barber,mutex--控制对变量waiting的互斥访问
Semaphore customers=0,barber=1,mutex=1;
int waiting=0;
begin 
	parbegin
	//barber:
		begin
			repeat
				wait(custmers);//有无顾客理发
				wait(mutex);
				waiting--;
				signal(mutex);//释放冲突变量
				cutting;
				signal(barber)//释放理发师
			until false;
		end
	//customers:
		begin
			repeat
				wait(mutex);
				if(waiting<chairs)
					then begin
						waiting++;//等待顾客+1
						signal(customers);//有顾客要理发
						signal(mutex);
						wait(barber);//申请理发师
						getting haircut;
					end
					else signal(mutex);//满员则离店
				until false;
			end
		parend
	end

理发师问题是操作系统经典同步问题中——生产者-消费者问题的典例,通常使用互斥信号量mutex用于控制对缓冲区的互斥访问,初始化为1。该问题又称为有限缓冲问题。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的理发师问题的 Python 代码实现,使用了队列来模拟等待顾客的过程: ```python class BarberShop: def __init__(self, barber, chairs): self.barber = barber self.chairs = chairs self.customers = [] def add_customer(self, customer): if len(self.customers) < self.chairs: self.customers.append(customer) return True return False def get_next_customer(self): if len(self.customers) > 0: return self.customers.pop(0) return None def run(self, time): for i in range(time): if self.barber.is_sleeping(): customer = self.get_next_customer() if customer is not None: self.barber.start_cutting(customer) else: self.barber.finish_cutting() class Barber: def __init__(self): self.is_sleep = True self.customer = None def is_sleeping(self): return self.is_sleep def start_cutting(self, customer): self.customer = customer self.is_sleep = False def finish_cutting(self): self.customer = None self.is_sleep = True class Customer: def __init__(self, time): self.time = time def main(): shop = BarberShop(Barber(), 3) shop.add_customer(Customer(10)) shop.add_customer(Customer(5)) shop.add_customer(Customer(15)) shop.run(30) if __name__ == '__main__': main() ``` 在这个例子中,我们创建了一个理发店对象 `BarberShop`,包括了一个理发师对象 `Barber` 和一些等待的顾客对象 `Customer`。`BarberShop` 中的 `add_customer` 方法用于添加一个新顾客到等待队列中,`get_next_customer` 方法用于获取下一个需要理发的顾客。`BarberShop` 中的 `run` 方法用于模拟一段时间内的理发过程,其中会检查理发师是否正在睡觉,如果是则唤醒下一个顾客,如果不是则完成当前顾客的理发过程。 在主函数中,我们创建了一个 `BarberShop` 对象,并添加了三个顾客到等待队列中,然后运行了 30 个时间单位的理发过程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值