Saturday, 16 February 2008

Erlang guards

Like matches, which are a very powerful instrument to split a large complex function into short better maintainable, this can also be supported through guards. Lets take for example a server using internally a process pool. This pool shall only provide the managed active processes until a maximum number, and take them back until a maximum number of free ones is reached. So the functions may be

handle_cast({do_it, Task}, S) when S#state.actno >= ?MAX_ACT_NO ->
    % Too much active processes, resend message.
    gen_server:cast(?MODULE, {do_it, Task}),
    {noreply, S};
handle_cast({do_it, Task}, S) when S#state.freeno > 0 ->
    % Use a free process.
    ...
    {noreply, NewS};
handle_cast({do_it, Task}, S) ->
    % Create a new process and use it.
    ...
    {noreply, NewS};
handle_cast({return_it, Proc}, S) when S#state.freeno >= ?MAX_FREE_NO ->
    % Dispose process.
    ...
    {noreply, NewS};
handle_cast({return_it, Proc}, S) -> 
    % Return the worker to the pool.
    ...
    {noreply, NewS}.

0 Comments: