Skip to content

Instantly share code, notes, and snippets.

@darcros
Created June 29, 2020 16:00
Show Gist options
  • Save darcros/7eef42188e390961649359e3dbf38e21 to your computer and use it in GitHub Desktop.
Save darcros/7eef42188e390961649359e3dbf38e21 to your computer and use it in GitHub Desktop.
Concurrent Programming in Erlang - The University of Kent - chapter 2.3
-module(frequency).
-export([init/0, loop/1]).
allocate({[], Allocated}, _Pid) ->
{{[], Allocated}, {error, no_frequency}};
allocate({[Freq | Free], Allocated}, Pid) ->
case lists:keymember(Pid, 2, Allocated) of
true -> {{[Freq | Free], Allocated}, {error, already_allocated}};
false -> {{Free, [{Freq, Pid} | Allocated]}, {ok, Freq}}
end.
deallocate({Free, Allocated}, {Freq, Pid}) ->
case lists:keyfind(Freq, 1, Allocated) of
{Freq, Pid} ->
NewAllocated = lists:delete({Freq, Pid}, Allocated),
{{[Freq | Free], NewAllocated}, ok};
{Freq, _} ->
{{Free, Allocated}, unauthorized};
false ->
{{Free, Allocated}, not_allocated}
end.
loop(Frequencies) ->
receive
{request, Pid, allocate} ->
{NewFrequencies, Reply} = allocate(Frequencies, Pid),
Pid ! {reply, Reply},
loop(NewFrequencies);
{request, Pid, {deallocate, Freq}} ->
{NewFrequencies, Reply} = deallocate(Frequencies, {Freq, Pid}),
Pid ! {reply, Reply},
loop(NewFrequencies);
{request, Pid, stop} ->
Pid ! {reply, stopped}
end.
init() ->
Frequencies = [10, 11, 12],
Server = spawn(?MODULE, loop, [{Frequencies, []}]),
register(?MODULE, Server).
Eshell V10.1 (abort with ^G)
1> c(frequency).
{ok,frequency}
2> frequency:init().
true
3> frequency ! {request, self(), allocate}.
{request,<0.74.0>,allocate}
4> flush().
Shell got {reply,{ok,10}}
ok
5> SomeOtherPid = pid(0, 255, 0).
<0.255.0>
6> frequency ! {request, SomeOtherPid, {deallocate, 10}}.
{request,<0.255.0>,{deallocate,10}}
7> flush().
ok
8> frequency ! {request, self(), {deallocate, 10}}.
{request,<0.74.0>,{deallocate,10}}
9> flush().
Shell got {reply,ok}
ok
10> frequency ! {request, self(), {deallocate, 10}}.
{request,<0.74.0>,{deallocate,10}}
11> flush().
Shell got {reply,not_allocated}
ok
12> frequency ! {request, self(), allocate}.
{request,<0.74.0>,allocate}
13> frequency ! {request, self(), allocate}.
{request,<0.74.0>,allocate}
14> flush().
Shell got {reply,{ok,10}}
Shell got {reply,{error,already_allocated}}
ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment