Created
October 21, 2021 11:11
-
-
Save NaurisSadovskis/39456afe99c6e3eb4de0f8628fb6c814 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%%------------------------------------------------------------------- | |
%%% @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