-module(resourcearbiterinclass). -export([start/0,init/0]). start() -> spawn(?MODULE, init, []). % The state is % a tuple {state, Status, Queue} % where Status is an atom, either free or inUse % and Queue is a list of process ids % where the head of the list is the next to get the resource % and the elements following are in order from oldest to youngest % requests % invariant: Status == free or Status == inUse, % and if Status is free then Queue is [] % and if Queue is not empty, then Status == inUse init() -> loop({state, free, []}). loop({state, Status, Queue}) -> receive {Pid, status} -> Pid ! Status, loop({state, Status, Queue}); {Pid, reserve} -> case Status of free -> Pid ! reserved, loop({state, inUse, Queue}); inUse -> loop({state, inUse, Queue ++ [Pid]}) end; {_Pid, release} -> case Queue of [] -> loop({state, free, Queue}); [Oldest|RestOfWaiting] -> Oldest ! reserved, loop({state, inUse, RestOfWaiting}) end end.