Esteu aquí: Inici Assignatures Programació Concurrent i en Temps Real Erlang: Exemples ping_pong.erl

ping_pong.erl

ping_pong.erl — Erlang source code, 713 bytes

Continguts del fitxer

-module(ping_pong).
-export([inici/0, inici/1, ping/2, pong/0]).

inici() ->
    inici(10).

inici(Max) -> 
    Pong = spawn(ping_pong, pong, []),
    Ping = spawn(ping_pong, ping, [Pong, Max]),
    Ping ! pong,
    ok.

ping(Pong, Max) ->
    receive
        pong when Max > 0 ->
            io:format("Ping ~p~n", [Max]),
            Pong ! {self(), ping, Max},
            ping(Pong, Max -1);
        _ ->
            Pong ! finalitzar,
            io:format("Ping fet~n")
    end.

pong() ->
    receive
        {Ping, ping, Max} ->
            io:format("Pong ~p~n", [Max]),
            Ping ! pong,
            pong();
        _ ->
            io:format("Pong fet~n")
    end.