【问题标题】:How to make Processes Run Parallel in Erlang?如何使进程在 Erlang 中并行运行?
【发布时间】:2011-02-10 11:25:10
【问题描述】:

startTrains() -> 总距离 = 100, 火车 = [trainA,trainB], PID = spawn(fun() -> 火车(1,长度(火车))结束), [PID! {self(),TrainData,TotalDist} ||火车数据 error_logger:info_msg("~n 消息 ~p ~n",[消息]) 10500 之后 -> 刷新 结束。

所以,我创建了两个名为 trainA、trainB 的进程。我想将这些过程增加 5 直到达到 100。我制作了不同的过程以使每个火车(过程)并行增加其位置。但是我很惊讶按顺序获得输出,即过程 trainA 结束,然后过程 trainB 开始。但我想同时增加自己。 我想运行这样的进程


trainA 10 trainB 0
trainA 15 trainB 5
....
trainA 100 trainB 100 

但我得到了


trainA 0
....
trainA 90
trainA 95
trainA 100
trainA ends

trainB 0
trainB 5
trainB 10
.....
trainB 100

如何使进程并行/同时运行?希望你能得到我的Q。请帮帮我。

【问题讨论】:

    标签: erlang process parallel-processing


    【解决方案1】:

    您只生成一个由函数train/2 初始化的进程。您提供的代码不完整,所以我只能猜测,但我认为您的代码是错误的,因为您只有一个火车流程。灵感来源:

    -module(trains).
    
    -export([startTrains/0]).
    
    startTrains() ->
      TotalDist = 100,
      Names = [trainA,trainB ],
      Self = self(),
      Trains = [spawn_link(fun() -> 
              train(Name, Self) end) || Name <- Names],
      [ Train ! {start, Self, 0, TotalDist} || Train <- Trains],
      ok = collectResults(Names).
    
    collectResults([]) -> ok;
    collectResults(Trains) ->
      receive
        {stop, Name, Pos, Length} ->
          io:format("~p stops at ~p (~p)~n", [Name, Pos, Length]),
          collectResults(Trains -- [Name]);
        Msg ->
          io:format("Supervisor received unexpected message ~p~n", [Msg]),
          collectResults(Trains)
      after 10500 -> timeout
      end.
    
    train(Name, Sup) ->
      receive
        {start, Sup, Pos, Length} -> run_train(Name, Sup, Pos, Length);
        Msg ->
          io:format("~p received unexpected message ~p~n", [Name, Msg]),
          train(Name, Sup)
      end.
    
    run_train(Name, Sup, Pos, Length)
      when Pos < Length ->
        receive after 500 ->
            NewPos = Pos + 5,
            io:format("~p ~p~n", [Name, Pos]),
            run_train(Name, Sup, NewPos, Length)
        end;
    run_train(Name, Sup, Pos, Length) ->
      Sup ! {stop, Name, Pos, Length}.
    

    但如果我认真考虑的话,我应该看看 gen_fsm 和 OTP 原则。但是在您当前的阶段,请继续使用 erlang 原语,以便首先获得更好的感觉。

    【讨论】:

    • 非常感谢! :) 你让我今天一整天都感觉很好。我正在为我的硕士用 Erlang 编写“防碰撞铁路系统”。我想演示我的调度程序来模拟火车。是的,你完全正确!我只是在创建一个进程并发送两列火车进程来运行(这确实是一个顺序运行)。
    猜你喜欢
    • 2013-02-08
    • 2012-12-14
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 2018-08-28
    • 2011-10-28
    相关资源
    最近更新 更多