Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

自習メモ〜コンカレントプログラミング

公開されているpdfの続きで、今日はコンカレントプログラミングということで、以下のようなプロセスのサンプル。

-module(pair).
-export([start/0, loop/1, client/2, client_proc/2, example/0]).

start() ->
    spawn(?MODULE, loop, [{}]).

loop({}) ->
    receive
        A ->
            loop({A})
    end;
loop({A}) ->
    receive
        B ->
            A ! {A, B},
            B ! {B, A},
            loop({})
    end.

client(Server, MyName) ->
    spawn(?MODULE, client_proc, [Server, MyName]).

client_proc(Server, MyName) ->
    Server ! self(),
    receive
        {_Self, Other} ->
            Other ! MyName,
            receive
                YourName ->
                    io:format("Hello ~s, My name is ~s~n", [YourName, MyName])
            end
    end.

example() ->
    Server = pair:start(),
    client(Server, "Alice"),
    client(Server, "Bob"),
    client(Server, "Thomas"),
    client(Server, "Tom"),
    client(Server, "Jerry"),
    client(Server, "Bull"),
    client(Server, "hoge").

だんだん頭が煮えてきました。。。まともに構文押さえないと、結構辛くなってきた。さすがにマニュアル調べながらやらないとどうにもならないので、namazuで検索できるようにしてみた。

以下、本日のメモ。

  • 「!」でメッセージ送信、receiveで受信
    • TODO:もう一回押さえとく
  • spawnの意味
    • プロセスを起動する
    • 実際にはerlangモジュールだが、auto-importされるのでモジュール名を指定する必要がない
   spawn(Module, Function, Args) -> pid()

   Types:
       Module = Function = atom()
       Args = [term()]

   Returns the pid of a new process started by the application of 
   Module:Function to Args. The new process created will be placed
   in the system scheduler queue and be run some time later. 
  • ?MODULE
    • The name of the current module.
    • マクロ