Last active
January 2, 2016 18:19
-
-
Save practicingruby/8342759 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-module(chopstick). | |
-export([start/1, loop/2]). | |
start(Number) -> | |
spawn(chopstick, loop, [Number, nobody]). | |
loop(Number, Owner) -> | |
receive | |
{take, Owner} -> loop(Number, Owner); | |
{take, NewOwner} when Owner =:= nobody -> | |
NewOwner ! {cs, Number}, | |
loop(Number, NewOwner); | |
{drop, Owner} -> | |
loop(Number, nobody) | |
end. |
This file contains hidden or 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
-module(philosophers). | |
-export([dine/0, loop/3]). | |
dine() -> | |
[C1, C2, C3, C4, C5] = [chopstick:start(X) || X <- [1,2,3,4,5]], | |
dine(C1, C2, C3, C4, C5). | |
% Attempts to use a resource hierarchy solution, which is probably | |
% inelegant in Erlang. Links to better implementations welcome! | |
dine(C1, C2, C3, C4, C5) -> | |
Aristotle = spawn(philosophers, loop, ["Aristotle", C1, C2]), | |
Popper = spawn(philosophers, loop, ["Popper", C2, C3]), | |
Epictetus = spawn(philosophers, loop, ["Epictetus", C3, C4]), | |
Heraclitus = spawn(philosophers, loop, ["Heraclitus", C4, C5]), | |
Schopenhauer = spawn(philosophers, loop, ["Schopenhauer", C1, C5]), | |
Aristotle ! Popper ! Epictetus ! Heraclitus ! Schopenhauer ! think. | |
loop(Philosopher, LeftChopstick, RightChopstick) -> | |
receive | |
think -> | |
io:format("~p is thinking.~n", [Philosopher]), | |
timer:sleep(1000), | |
self() ! eat; | |
eat -> | |
LeftChopstick ! {take, self()}, | |
receive | |
{cs, FirstChopstick} -> | |
io:format("~p picked up chopstick ~p~n", [Philosopher, FirstChopstick]), | |
RightChopstick ! {take, self()}, | |
receive | |
{cs, SecondChopstick} -> | |
io:format("~p picked up chopstick ~p~n", [Philosopher, SecondChopstick]), | |
io:format("~p is eating.~n", [Philosopher]), | |
timer:sleep(1000) | |
end | |
end, | |
LeftChopstick ! {drop, self()}, | |
RightChopstick ! {drop, self()}, | |
io:format("~p is done eating, releases chopsticks ~p and ~p~n", | |
[Philosopher, FirstChopstick, SecondChopstick]), | |
self() ! think | |
end, | |
loop(Philosopher, LeftChopstick, RightChopstick). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment