Erlangでブロードキャスト

30分プログラム、その582。Erlangでブロードキャスト。

ふと、Erlangのメッセージ送信って一個のプロセスしか送れないから、複数のプロセスにメッセージを送るライブラリがあってもいいかな、と思ったので書いてみた。

ふと、思っただけなので、特に意味も実用性もない。

使い方

example() ->
    B0 = bcast:create(),
    B1 = bcast:add(B0,spawn(fun () -> receive
				    Msg ->
					io:format("A: ~p~n",[Msg])
				end
		      end)),
    B2 = bcast:add(B1,spawn(fun () -> receive
				    Msg ->
					io:format("B: ~p~n",[Msg])
				end
		      end)),
    bcast:send(B2, bcast_msg).
1> bcast:example().
A: bcast_msg
B: bcast_msg
ok

ソースコード

-module(bcast).
-compile([export_all]).

create() ->
    [].

add(BCast,Pid) ->
    [Pid|BCast].

send(BCast, Msg) ->
    lists:foreach(fun(Pid) -> Pid ! Msg end, BCast).

example() ->
    B0 = create(),
    B1 = add(B0,spawn(fun () -> receive
				    Msg ->
					io:format("A: ~p~n",[Msg])
				end
		      end)),
    B2 = add(B1,spawn(fun () -> receive
				    Msg ->
					io:format("B: ~p~n",[Msg])
				end
		      end)),
    send(B2, bcast_msg).