在Erlang的许多进程中创建列表 [英] Create list across many processes in Erlang

查看:194
本文介绍了在Erlang的许多进程中创建列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我甚至很难想像如何描述我需要的东西。但这真的很简单。我想产生n个生成n个ID的进程。我有一些简单的递归和打印到终端。我正在努力创建一个列表可以访问每个这些生成的进程,我可以积累ids。那么,当进程完成后,我需要打印出任何副本。



我尝试了几个不同的选项与ets表,它总是打印一个没有列表。我认为是因为在进程完成之前我已经得到了打印功能?我知道我在想这个错误,但是会非常感谢在正确的方向微调。

解决方案

你需要同步你的主过程与产生的进程。您可以通过从每个id生成器进程发送消息到主服务器,并且后者将等待所有进程报告。

  master(N) - > 
%%我们需要一个这个过程的一个pid来为奴隶发送消息到
Self = self(),

%%生成从属进程并保存其pids
Pids = [spawn(fun() - > slave(Self)end || list:seq(1,N)],

%%从每个从属进程接收id消息
Ids = [recv_id(Pid)|| Pid< - Pids],

%%使用这里的数据做任何我们想要的数据
find_duplicates(Ids)

slave(Master) - >
Id = mk_id(),

%%向master发送消息
Master!{id,self(),Id

recv_id(Pid) - >
接收
{id,Pid,Id} - > Id
end。

mk_id() - > ...
find_duplicates(Ids) - > ...


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.

解决方案

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) -> ...

这篇关于在Erlang的许多进程中创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆