Erlang 实现互斥量

来源:互联网 发布:阿里云部署git服务器 编辑:程序博客网 时间:2024/05/16 05:45


#以下代码片段来自"Erlang编程指南",  值得注意一点的是stop/0函数发送停止消息以后, mutex进程仅在free状态下处理, 也就是说如果目前mutex没有人使用,直接结束mutex,如果正在使用,并且有等待在此信号量上的其他进程,那么这些正在使用的进程和正在queue的进程依然可以获取到mutex执行完他们的任务,  但是所有在stop信号之后的wait调用就不会被处理了, 很合理的处理.


-module(mutex).
-export([start/0, stop/0]).
-export([wait/0, signal/0]).
-export([init/0]).
start()->
    register(mutex, spawn(?MODULE, init, [])).


stop()->
    mutex ! stop().


wait()->
    mutex ! {wait, self()},
    receive
         ok->
             ok  
         end.
 
signal()->
    mutex ! {signal, self()}, 
ok.


init()->
    free().

free()->
    receive
   {wait, Pid}->
   Pid ! ok,
busy(Pid);
stop->
   terminate()
end.

busy(Pid)->
    receive  
   {signal, Pid}->
   free()
end.


terminate()->
    receive
   {wait, Pid}->
   exit(Pid, kill),
terminate()
after
   0->
  ok
end.


##博客仅作个人记录##


0 0
原创粉丝点击