问题
Ok, I am even having a hard time thinking of how to describe what I need. But it is really quite simple. I want to spawn n number of processes that generate n number of IDs. I have this working with some simple recursion and printing to the terminal. Where I am struggling is creating a list accessible to each of these spawned processes where I can accumulate the ids. then, when the processes are complete, I need to print-out any duplicates.
I tried a few different options with ets tables and it always prints a list of nothing. I presume because I get to the printing function before the processes have completed? I know I am thinking of this wrong but would greatly appreciate a nudge in the right direction.
回答1:
You need to synchronize your main process with the spawned processes. You can do that by sending a message from each of the id generator processes to the main, and the latter would wait for all the processes to report.
master(N) ->
%% we need a pid of this process for the slaves to send messages to
Self = self(),
%% spawn slave processes and save their pids
Pids = [spawn(fun() -> slave(Self) end || lists:seq(1, N)],
%% receive id message from each of the slave processes
Ids = [recv_id(Pid) || Pid <- Pids],
%% do whatever we want with the data here
find_duplicates(Ids).
slave(Master) ->
Id = mk_id(),
%% send a message to the master
Master ! {id, self(), Id}.
recv_id(Pid) ->
receive
{id, Pid, Id} -> Id
end.
mk_id() -> ...
find_duplicates(Ids) -> ...
来源:https://stackoverflow.com/questions/19823512/create-list-across-many-processes-in-erlang