Weitere ähnliche Inhalte
Ähnlich wie Erlangのマルチプロセスを触ってみた (8)
Mehr von Yoichi Toyota (20)
Erlangのマルチプロセスを触ってみた
- 3. ! 1つのファイルにまとめられた関数群
=== test1.erl ===
-module(test1)
-export([add/2])
add(a, b) ->
a + b.
=== test1.erl ===
1> c(test1)
{ok,test1}
2> test1:add(1, 2).
3
モジュール名の宣言
このモジュールで外部に公開する関数の宣言
関数定義
- 5. ! ガード
◦ パターンマッチより詳細な条件を記述
torpedo_submarine(Level, Ko_Hyoteki) ->
when Ko_Hyoteki =:= true ; Level >= 10
true;
torpedo_submarine(_, _) ->
false.
1> test1:torpedo_submarine(12, false).
true
2> test1:torpedo_submarine(8, true).
true
3> test1:torpedo_submarine(8, false).
false
- 6. !
ガードと似ている
night_combat(MainWeapon, SubWeapon, Torpedo) ->
if Torpedo >= 2 ;
MainWeapon >= 3 ;
MainWeapon =:= 2 andalso SubWeapon >= 1 ;
MainWeapon >= 1 andalso MainWeapon =< 2 andalso Torpedo =:= 1 ->
cutin;
MainWeapon =:= 2 andalso SubWeapon =:= 0 andalso Torpedo =:= 0 ;
MainWeapon =:= 1 andalso SubWeapon >= 1 andalso Torpedo =:= 0 ;
MainWeapon =:= 0 andalso SubWeapon >= 2 andalso Torpedo =< 1 ->
'double strike';
true ->
'single strike'
end.
1> test1:night_combat(1, 1, 1).
cutin
2> test1:night_combat(1, 0, 0).
‘single strike’
- 8. ! !
(Bang)
◦ Pidにメッセージを送信する
1> self() ! hello.
hello
2> self() ! ‘hello world’.
‘hello world’
3> flush().
Shell got hello
Shell got 'hello world'
ok
- 9. receive
!
◦ メッセージを受信
1> Func = fun() ->
receive
{Pid, N} when N rem 2 =:= 0 -> Pid ! even;
{Pid, _} -> Pid ! odd;
end
end.
#Fun<erl_eval.20.80484245>
2> Rmt = spawn(Func).
<0, 34, 0>
3> Rmt ! {self(), 4}.
{self(), 4}
4> flush().
Shell got even
ok
- 13. ! モニター開始/終了
◦ erlang:monitor(process, Pid) -> Ref
" Pidのプロセスをモニター開始
◦ erlang:demonitor(Ref) -> true
" モニター終了
! 監視している側にメッセージが届く
◦ { DOWN , Ref, process, Pid, Reason}
" DOWN :シンボル
" Ref:監視しているモニターオブジェクトの参
照
" Pid:死んだプロセスのID
" Reason:プロセスが死んだ理由