【问题标题】:erlang semaphore (mutex)erlang 信号量(互斥体)
【发布时间】:2011-04-10 19:15:42
【问题描述】:

我在 erlang 中找到了互斥锁的例子

有人可以修改它以将其与信号量之类的计数一起使用吗?

-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.

【问题讨论】:

  • 您希望界面是什么样的?

标签: erlang


【解决方案1】:

这不是最好的信号量.. 可以使用一些随机的东西,但希望你能明白。

-module(sem1).
-export([semaphor/2, start/1, start/0]).

semaphor(0,0) ->
    io:format("err");

semaphor(0,Full)->
    receive
        {increment,PID} ->
            io:format("UP ~w ~w~n", [0,PID]),
            PID ! {incGranted},
            semaphor(1,Full)
    end;


semaphor(Full,Full)->
    receive
        {decrement,PID} ->
            io:format("DOWN ~w ~w~n", [Full,PID]),
            PID ! {decGranted},
            semaphor(Full -1 , Full)
    end;

semaphor(N,Full)->
    receive
        {decrement,PID} ->
            io:format("DOWN ~w ~w~n", [N,PID]),
            PID ! {decGranted},
            semaphor(N -1 , Full);
        {increment,PID} ->
            io:format("UP ~w ~w~n", [N,PID]),
            PID ! {incGranted},
            semaphor(N + 1 , Full)
    end.

start(PID) ->
    PID ! {decrement, self()},
    receive
        {decGranted} -> true
    end,
    timer:sleep(100),
    PID ! {increment, self()},
    receive
        {incGranted} -> true
    end,
    start(PID).

start() ->
    PID = spawn(sem1, semafor, [1,5]),
    spawn(sem1,start,[PID]),
    spawn(sem1,start,[PID]),
    spawn(sem1,start,[PID]),
    spawn(sem1,start,[PID]),
    spawn(sem1,start,[PID]),
    spawn(sem1,start,[PID]).

【讨论】:

    猜你喜欢
    • 2017-08-24
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 2012-09-01
    • 2011-01-05
    • 1970-01-01
    相关资源
    最近更新 更多