Created
May 31, 2011 11:27
-
-
Save elisehuard/1000339 to your computer and use it in GitHub Desktop.
sleeping barber in erlang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% sleeping barber problem | |
-module(sleeping_barber). | |
-export([barber_scenario/0]). | |
start_shop() -> | |
spawn(fun() -> barber_shop() end) | |
. | |
barber_scenario() -> | |
ShopPid = start_shop(), | |
% send customers as tuples to the shop | |
ShopPid ! 'john', | |
ShopPid ! 'joe', | |
timer:sleep(20000), | |
ShopPid ! 'kevin', | |
ShopPid ! 'richard', | |
main_end. | |
%% barber %% | |
barber(ShopPid) -> | |
ShopPid ! barbercheck, | |
receive | |
wakeup -> | |
barber(ShopPid); | |
{customer, Customer} -> | |
cut(ShopPid, Customer), | |
barber(ShopPid) | |
end. | |
cut(ShopPid, Name) -> | |
io:format("cutting ~p~n", [Name]), | |
% take customer -> can be removed from waiting chairs | |
ShopPid ! {cut, Name}, | |
timer:sleep(random:uniform(10000)), | |
io:format("done transforming ~p in shepherd's pie~n", [Name]). | |
%% shop %% | |
barber_shop() -> | |
io:format("lights on ... ~n"), | |
ShopPid = self(), | |
BarberPid = spawn(fun() -> barber(ShopPid) end), | |
barber_shop_in_business(BarberPid, []). | |
barber_shop_in_business(BarberPid, CustomersInChairs) -> | |
receive | |
{cut, Customer} -> | |
% pop customer from list when hair is being cut | |
remove_customer_from_chair(BarberPid, CustomersInChairs, Customer); | |
barbercheck -> | |
respond_to_barber(BarberPid, CustomersInChairs); | |
Customer -> | |
io:format("~p arrives~n",[Customer]), | |
% should check the number of customers waiting first | |
% if all full: customer turned away | |
add_customer_if_available(BarberPid, CustomersInChairs, Customer) | |
end. | |
respond_to_barber(BarberPid, []) -> | |
% BarberPid ! no, | |
barber_shop_in_business(BarberPid, []); | |
respond_to_barber(BarberPid, [First|Next]) -> | |
BarberPid ! {customer, First}, | |
% making sure to send the customer to the barber only once. | |
barber_shop_in_business(BarberPid, Next). | |
remove_customer_from_chair(BarberPid, List, Customer) -> | |
barber_shop_in_business(BarberPid, lists:delete(Customer,List)). | |
% assuming 3 chairs | |
add_customer_if_available(BarberPid, List, Customer) when length(List) >= 3 -> | |
io:format("Sorry ~p, no room~n",[Customer]), | |
% continue with the original customers | |
barber_shop_in_business(BarberPid, List); | |
add_customer_if_available(BarberPid, List, Customer) -> | |
% let's tell the barber in case he is sleeping | |
BarberPid ! wakeup, | |
barber_shop_in_business(BarberPid, lists:append(List, [Customer])). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment