-module(dining3). -export([start/1,stickDown/0,phil/3]). start(N) when N>=2 -> Sticks = createSticks(N), startPhils(lists:last(Sticks),Sticks,0). createSticks(0) -> []; createSticks(N) when N>0 -> [spawn(dining3,stickDown,[])|createSticks(N-1)]. startPhils(SL,[],_) -> ok; startPhils(SL,[SR|Sticks],N) -> spawn(dining3,phil,[SL,SR,N]), startPhils(SR,Sticks,N+1). stickDown() -> receive {take,P} -> P!took, stickUp(); {getState,P} -> P!down, stickDown() end. stickUp() -> receive put -> stickDown(); {getState,P} -> P!up, stickUp() end. take(Stick) -> Stick!{take,self()}, receive took -> ok end. phil(SL,SR,N) -> io:format("~w is thinking~n",[N]), %timer:sleep(100*N), io:format("~w is getting hungry~n",[N]), take(SL), io:format("~w took left stick~n",[N]), SR!{getState,self()}, receive up -> SL!put, io:format("~w returned left stick~n",[N]), phil(SL,SR,N); down -> take(SR), io:format("~w took right stick~n",[N]), io:format("~w is eating~n",[N]), %timer:sleep(100*N), SL!put, io:format("~w put left stick~n",[N]), SR!put, io:format("~w put right stick~n",[N]), phil(SL,SR,N) end.