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

bvn4nwqk  于 2023-09-28  发布在  Erlang
关注(0)|答案(1)|浏览(167)
startTrains() ->
    TotalDist = 100,
    Trains = [trainA,trainB ],
    PID = spawn(fun() -> 
            train(1,length(Trains)) end),
    [ PID ! {self(),TrainData,TotalDist} || TrainData <- Trains],
    receive
    {_From, Mesg} ->
        error_logger:info_msg("~n Mesg ~p ~n",[Mesg])
            after 10500 ->
        refresh
    end.

因此,我创建了两个进程,分别命名为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。请帮帮我

dxpyg8gm

dxpyg8gm1#

只生成一个由函数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原语,以获得更好的感觉。

相关问题