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个消息.

  • 相关阅读:
    谈谈我对服务熔断、服务降级的理解
    PS-AXI-GPIO-流水灯设计
    立创EDA的使用
    multisim的操作回顾
    verilog的文件流和项目流
    AXI4的主从机的收发机制
    AXI4协议的物理模型
    verilog中的数据类型
    matlab的基本操作
    ARM之AXI总线协议初试
  • 原文地址:https://www.cnblogs.com/bobolive/p/3189464.html
Copyright © 2011-2022 走看看