I want to test a mutex semaphore written in Erlang. The exported functions are:
- start/0, -> To start the mutex server.
- stop/0, -> To stop the mutex server.
- wait/0, -> To put the semaphore in busy state.
- signal/0, -> To free the semaphore.
Then, From an erlang console:
mutex:start().
mutex:wait().
How do I execute another mutex:wait() to test the semaphore?
I tried creating 2 erlang nodes (erl -sname), and using rpc:call(node, mutex, wait, []) I can do that but when i try the signal – rpc:call(node, mutex, signal, []) – it creates another Pid different from the one that makes the wait call, so the semaphore is never liberated.
Appreciate your help. Thanks!.
This is the code if needed * From Erlang Programming Book *
-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.
From the shell do:
Off the top of my head so no return values here. You can also make it more interesting by spawning more processes and maybe including sleeps in them so they wait and signal in a more complex fashion.