如何使进程在Erlang中并行运行?

时间:2010-04-21 07:06:48

标签: erlang process parallel-processing

startTrains() - >     TotalDist = 100,     火车= [trainA,trainB],     PID = spawn(fun() - >             火车(1,长度(火车))结束),     [PID! {self(),TrainData,TotalDist} || TrainData< - Trains],     接收     {_From,Mesg} - >         error_logger:info_msg(“~n Mesg~p~n”,[Mesg])             在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.请帮帮我。

1 个答案:

答案 0 :(得分:6)

您只生成一个由函数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原语来先获得更好的感受。