Skip to content

Instantly share code, notes, and snippets.

@NaurisSadovskis
Created October 21, 2021 11:11
Show Gist options
  • Save NaurisSadovskis/39456afe99c6e3eb4de0f8628fb6c814 to your computer and use it in GitHub Desktop.
Save NaurisSadovskis/39456afe99c6e3eb4de0f8628fb6c814 to your computer and use it in GitHub Desktop.
%%%-------------------------------------------------------------------
%%% @author tcz
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 20. Oct 2021 17:08
%%%-------------------------------------------------------------------
-module(mutex).
-author("tcz").
%% API
-export([start/0, init/0, test/0, testinit/0]).
start() ->
register(mutex, spawn(?MODULE, init, [])).
stop() ->
mutex ! stop.
init() ->
process_flag(trap_exit, true),
free().
wait() -> call(wait).
signal() -> call(signal).
test() ->
spawn(?MODULE, testinit, []).
testinit() ->
io:format("Acquiring lock for process ~p...~n", [self()]),
wait(),
receive _ -> {} end.
call(Message) ->
mutex ! {Message, self()},
receive
{reply, Reply} -> Reply
end.
reply(Pid, Message) ->
Pid ! {reply, Message}.
free() ->
receive
{wait, Pid} ->
link(Pid),
reply(Pid, ok),
busy(Pid)
end.
busy(Pid) ->
receive
{signal, Pid} ->
unlink(Pid),
reply(Pid, ok),
free();
{'EXIT', Pid, Reason} ->
io:format("Process exited for reason ~p~n", [Reason]),
unlink(Pid),
free()
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment