您的位置:首页 > 其它

Erlang 实现互斥量

2017-01-05 07:15 190 查看
#以下代码片段来自"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.

##博客仅作个人记录##
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: