Assignment 2
Due Date: February, 16 2012
For this assignment, you will use Erlang to implement the dining
philosophers problem and samefringe.
Erlang is available on the departmental machines, but you can download
a copy for yourself from here. A
quick overview on how to get started with Erlang is available
here.
Part I
Implement the samefringe problem in Erlang. Given two trees
(represented as lists), your program should create two threads, each one
responsible for traversing one of the trees, communicating with one another
using Erlang message-passing primitives. Each thread traverses its
respective tree until its encounters an integer leaf node. One of the
threads (the master) communicates its leaf to the other (the slave); if they
match, an acknowledgement is sent, and both threads continue their
traversal. If they do not, a message is sent to terminate the search.
Part 2
For this part of the assignment, you will implement the dining philosophers
problem in Erlang. The code structure for some of the procedures is given
below. You will need to fill in the code for fork(),room(),
and philosophers(). Recall each philosopher thinks, enters the
room to eat, picks up the forks on his left and right, eats, puts down
the two forks, and exits. Observe that each of these entities are
represented
as Erlang processes.
start(N) ->
Control = spawn(fun () ->
Room = spawn_link(fun () -> room(0, N - 1) end),
Fork = spawn_link(fun fork/0),
setup(N, Room, Fork, Fork)
end),
register(dining_philosophers, Control),
ok.
setup(N, Room, Left, Last) when N > 1 ->
Right = spawn_link(fun fork/0),
spawn_link(fun () -> philosopher(N, Room, Left, Right) end),
setup(N - 1, Room, Right, Last);
setup(1, Room, Left, Right) ->
spawn_link(fun () -> philosopher(1, Room, Left, Right) end),
receive
_ -> exit({done})
end.
stop() ->
dining_philosophers ! stop,
unregister(dining_philosophers),
ok.
pause(Milliseconds) ->
receive after Milliseconds -> ok end.
say(Name, Pred) ->
io:format("Philosopher ~w ~s~n", [Name, Pred]).
eat(Name) ->
say(Name, "is eating."),
pause(3000).
think(Name) ->
say(Name, "is thinking."),
pause(500).