-module(cham). -export([start/1, start_perf/2, perf_test/3, creature/2, meeting_place/1, meeting_place/3]). -define(MEETINGS, 1000000). -define(NODE, second@pc). creature(Colour, MPPid) -> MPPid ! {self(), Colour}, creature(Colour, MPPid, 0). creature(Colour, MPPid, Met) -> receive faded -> MPPid ! Met; OColour when is_atom(OColour) -> NColour = complement({Colour, OColour}), MPPid ! {self(), NColour}, creature(NColour, MPPid, Met+1) end. meeting_place(N) -> meeting_place(N, 0, 0). meeting_place(0, _, TPid) -> end_meeting(0, 4, TPid); meeting_place(N, Cr, TPid) -> receive {CrPid, Colour} when is_tuple(Cr) -> {CrPid1, Colour1} = Cr, CrPid ! Colour1, CrPid1 ! Colour, % io:format("Cr1: ~p, Cr2: ~p~n", [CrPid, CrPid1]), meeting_place(N-1, 0, TPid); {CrPid, Colour} -> meeting_place(N, {CrPid, Colour}, TPid) end. end_meeting(TMet, 0, TPid) -> io:format("Total meetings: ~p~n", [TMet]), if is_pid(TPid) -> TPid ! 'end'; true -> 0 end; end_meeting(TMet, Crs, TPid) -> receive {CrPid, _} -> CrPid ! faded, end_meeting(TMet, Crs, TPid); Met when is_number(Met) -> end_meeting(TMet + Met, Crs-1, TPid) end. start(N) -> MPPid = spawn(?MODULE, meeting_place, [N]), spawn(?MODULE, creature, [blue, MPPid]), spawn(?MODULE, creature, [red, MPPid]), spawn(?MODULE, creature, [yellow, MPPid]), spawn(?MODULE, creature, [blue, MPPid]). complement(Pair) -> case Pair of {blue, red} -> yellow; {blue, yellow} -> red; {blue, blue} -> blue; {red, yellow} -> blue; {red, blue} -> yellow; {red, red} -> red; {yellow, yellow} -> yellow; {yellow, red} -> blue; {yellow, blue} -> red; {faded, _} -> faded; _Else -> erlang:error(badarg) end. start2(N, TPid) -> MPPid = spawn(?MODULE, meeting_place, [N, 0, TPid]), spawn(?MODULE, creature, [blue, MPPid]), spawn(?MODULE, creature, [red, MPPid]), spawn(?MODULE, creature, [yellow, MPPid]), spawn(?MODULE, creature, [blue, MPPid]). start2nodes(N, TPid) -> MPPid = spawn(?MODULE, meeting_place, [N, 0, TPid]), spawn(?NODE, ?MODULE, creature, [blue, MPPid]), spawn(?NODE, ?MODULE, creature, [red, MPPid]), spawn(?NODE, ?MODULE, creature, [yellow, MPPid]), spawn(?NODE, ?MODULE, creature, [blue, MPPid]). start_perf(N, Nodes) -> spawn(?MODULE, perf_test, [N, [], Nodes]). perf_test(0, R, _) -> Max = lists:max(R), Min = lists:min(R), Sum = lists:sum(R), Avg = (Sum - Max - Min) / (length(R) -2), io:format("Average execution time: ~p~n", [Avg]); perf_test(N, R, Nodes) -> T = now(), if Nodes == true -> start2nodes(?MEETINGS, self()); true -> start2(?MEETINGS, self()) end, receive 'end' -> D = timer:now_diff(now(), T) / 1000000, io:format("Total time elapsed: ~p~n", [D]), perf_test(N-1, [D | R], Nodes) end.