How to resolve the algorithm Metered concurrency step by step in the Erlang programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Metered concurrency step by step in the Erlang programming language
Table of Contents
Problem Statement
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active concurrent unit should attempt to acquire the counting semaphore before executing its assigned duties. In this case the active concurrent unit should report that it has acquired the semaphore. It should sleep for 2 seconds and then release the semaphore.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Metered concurrency step by step in the Erlang programming language
Source code in the erlang programming language
-module(metered).
-compile(export_all).
create_semaphore(N) ->
spawn(?MODULE, sem_loop, [N,N]).
sem_loop(0,Max) ->
io:format("Resources exhausted~n"),
receive
{release, PID} ->
PID ! released,
sem_loop(1,Max);
{stop, _PID} ->
ok
end;
sem_loop(N,N) ->
receive
{acquire, PID} ->
PID ! acquired,
sem_loop(N-1,N);
{stop, _PID} ->
ok
end;
sem_loop(N,Max) ->
receive
{release, PID} ->
PID ! released,
sem_loop(N+1,Max);
{acquire, PID} ->
PID ! acquired,
sem_loop(N-1,Max);
{stop, _PID} ->
ok
end.
release(Sem) ->
Sem ! {release, self()},
receive
released ->
ok
end.
acquire(Sem) ->
Sem ! {acquire, self()},
receive
acquired ->
ok
end.
start() -> create_semaphore(10).
stop(Sem) -> Sem ! {stop, self()}.
worker(P,N,Sem) ->
acquire(Sem),
io:format("Worker ~b has the acquired semaphore~n",[N]),
timer:sleep(500 * random:uniform(4)),
release(Sem),
io:format("Worker ~b has released the semaphore~n",[N]),
P ! {done, self()}.
test() ->
Sem = start(),
Pids = lists:map(fun (N) ->
spawn(?MODULE, worker, [self(),N,Sem])
end, lists:seq(1,20)),
lists:foreach(fun (P) -> receive {done, P} -> ok end end, Pids),
stop(Sem).
You may also check:How to resolve the algorithm Bitmap/Bézier curves/Cubic step by step in the F# programming language
You may also check:How to resolve the algorithm String concatenation step by step in the min programming language
You may also check:How to resolve the algorithm Include a file step by step in the D programming language
You may also check:How to resolve the algorithm Metered concurrency step by step in the Racket programming language
You may also check:How to resolve the algorithm Ackermann function step by step in the Go programming language