zoukankan      html  css  js  c++  java
  • erlang 练手 进程环

    Erlang 编程指南第四章 练习4-2

    编写一个程序,生成N个进程并相连成环,启动环后绕环发送M个消息,当收到退出消息后终止.

    ringStart(M,N,Message, Cp) ->
        io:format("ring start ~w|~w|~p~n",[M, N, Message]),
        if
            N > 0 ->
                Pid = spawn(test_pid, ringReader, [N, self(), yes, 0]),
                Pid ! {read, M, Message};
            true -> Pid = Cp
        end,
        receive
            {nextMsg, Ring} when Ring == 0 -> io:format("ring ok",[]);
            {nextMsg, Ring} -> io:format("nest ring start ~w~n",[Ring -1]), Pid ! {read, Ring - 1, Message}, ringStart(Ring -1, 0, Message, Pid)
        end.
    
    
    ringReader(N, Pid, Flg, Cp) ->
        io:format("start ~w~n",[N]),
        if
            N > 0 andalso Flg == yes ->
                CPid = spawn(test_pid, ringReader, [N-1, Pid, Flg, 0]);
            true -> CPid = Cp
        end,
        receive
            {read, Ring, Msg} -> 
            io:format("Reader ~w receive msg ~p~n",[N, Msg]),
            if
                N == 0 ->
                    io:format("P nextMsg ~w~n", [Pid]), Pid ! {nextMsg, Ring};
                true -> CPid ! {read, Ring, Msg}
            end,
             ringReader(N, Pid, no, CPid);
            stop -> io:format("Reader ~w stop ~n",[N])
        end.

    运行结果:

    通过io:format 可以清楚地看到3个进程结成一个环,并绕环发送了3个消息.

  • 相关阅读:
    关于vue的npm run dev和npm run build
    移动端meta行大全
    浅谈前端三大框架Angular、react、vue
    Web Workers
    Meta(其他信息)
    页面
    页面
    日期和时间
    ECharts教程(未完)
    页面
  • 原文地址:https://www.cnblogs.com/bobolive/p/3189464.html
Copyright © 2011-2022 走看看