| Paste number 26088: | master slave |
| Pasted by: | rhymes |
| 2 years, 3 months ago | |
| None | |
| Paste contents: |
| -module(master_slaves). -export([start/1, master/1, to_slave/2, build_procs/2, slave/0]). %% start the program, create the master process and tell it to create %% the slaves start(N) -> Master_PID = spawn(master_slaves, master, [[]]), register(master, Master_PID), io:format("master ~w created~n", [Master_PID]), Master_PID ! {create_procs, N}, ok. %% the master process: stores a list of linked slaves and %% recreates them upon failure master(PIDs) -> receive {create_procs, N} -> Procs_PIDs = build_procs(N, []), io:format("#~w slaves created~n", [N]), lists:map(fun(P) -> link(P) end, Procs_PIDs), process_flag(trap_exit, true), io:format("slaves linked to the master~n", []), master(Procs_PIDs); {Msg, N} -> PID = lists:nth(N, PIDs), PID ! Msg, master(PIDs); {'EXIT', PID, Reason} -> io:format("~w slave died of ~w~n", [PID, Reason]), lists:delete(PID, PIDs), New_PID = spawn(master_slaves, slave, []), lists:append([New_PID], PIDs), master(PIDs) end. %% used to communicate with the slaves to_slave(Msg, N) -> master ! {Msg, N}, io:format("~w~n", [{Msg, N}]). %% the slave slave() -> receive die -> exit(die); Msg -> io:format("~w slave received ~w command!~n", [self(), Msg]), slave() end. %% used to build the list of slaves build_procs(0, L) -> L; build_procs(N, L) -> List = lists:append(L, [spawn(master_slaves, slave, [])]), build_procs(N - 1, List). |
This paste has no annotations.