-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreliablemutex.erl
56 lines (47 loc) · 1.08 KB
/
reliablemutex.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-module(reliablemutex).
%%Interface
-export([start/0,wait/0,signal/0]).
%%Test
-export([test/1]).
%%Spawned exports
-export([free/0]).
start() ->
process_flag(trap_exit, true),
register(mutex, spawn(mutex, free, [])),
ok.
free() ->
receive
{Pid, wait} ->
catch link(Pid),
Pid ! {reply, ok},
io:format("~p made mutex change from free to busy~n", [Pid]),
busy(Pid)
end.
busy(Pid) ->
receive
{Pid, signal} ->
unlink(Pid),
Pid ! {reply, ok},
io:format("~p made mutex change from busy to free~n", [Pid]),
free();
{'EXIT', Pid, _Reason} ->
io:format("~p died the reasource has been freed~n",[Pid]),
free()
end.
call(Msg) ->
mutex ! {self(), Msg},
receive
{reply, Reply} ->
Reply
end.
wait() ->
call(wait).
signal() ->
call(signal).
test(Time) ->
io:format("Waiting for reasource ~p~n", [self()]),
reliablemutex:wait(),
io:format("Using reasource ~p~n", [self()]),
timer:sleep(Time),
io:format("Releasing the reasource ~p~n", [self()]),
reliablemutex:signal().