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:
1> mutex:start().
2> mutex:wait().
3> spawn(fun () -> mutex:wait(), io:format("Got it\n"), mutex:signal() end).
4> mutex:signal().
Got it
5>
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.
You shouldn't need two whole erlang VMs to test this. I wrote a lock server in erlang a long time ago (provides such things via a simple tcp-based protocol) and had a fairly complete test for the core:
https://github.com/dustin/elock/blob/master/src/lock_serv_test.erl
精彩评论