【问题标题】:Create list across many processes in Erlang在 Erlang 中跨多个进程创建列表
【发布时间】:2013-11-18 08:45:19
【问题描述】:

好吧,我什至很难考虑如何描述我的需求。但这真的很简单。我想生成 n 个生成 n 个 ID 的进程。我有一些简单的递归和打印到终端的工作。我正在苦苦挣扎的地方是创建一个列表,每个生成的进程都可以访问这些进程,我可以在其中积累 id。然后,当这些过程完成后,我需要打印出所有副本。

我用 ets 表尝试了几个不同的选项,但它总是打印一个没有任何内容的列表。我想是因为我在流程完成之前就进入了打印功能?我知道我的想法是错误的,但非常感谢您朝着正确的方向轻推。

【问题讨论】:

    标签: erlang


    【解决方案1】:

    您需要将主进程与衍生进程同步。您可以通过从每个 id 生成器进程向主进程发送消息来做到这一点,后者将等待所有进程报告。

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

    【讨论】:

      猜你喜欢
      • 2013-05-27
      • 2023-03-09
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 2013-09-27
      • 2016-11-28
      相关资源
      最近更新 更多