Workers

code

Implementation of workers

   worker(Compute) ->
       spawn (fun () -> worker_body(Compute) end ).

   worker_body(Compute) ->
            receive {Pid, Tasks} ->
                    Result = Compute(Tasks),
                    Pid ! {self(), Result},
                    worker_body(Compute)
            end.
  

Function pmap using workers

On lock based programming

Software Transactional Memories (STM)

We have two processes with two different transactions.

Transaction 1

Now, both transactions read their corresponding variables. Each transaction recalls the version number of the read variables.

Transaction 2

The transaction on the left firstly writes into variable x, and the transaction on the right follows but it fails (Why?) and retry.

Transaction 3

The transaction on the right retries.

Transaction 4

At the time of writing, it succeeds (Why?). Transaction 5

STM implementations

STM in Erlang

code

loop(Vars, {add, Name, Init}) ->
    case dict:find(Name, Vars) of
         {ok, _} -> {ok, Vars} ;
         error   -> {ok, dict:store(Name, {0,Init}, Vars)}
    end ;

loop(Vars, {pull, Name}) ->
    case dict:find(Name, Vars) of 
         {ok, {Ver, Value}} -> {{Name, Ver, Value}, Vars} ;
         _                  -> {error, Vars}
    end ;

loop(Vars, {push, Name, {Name, Ver, Value}}) ->
    {VerTM, _} = dict:fetch(Name, Vars),
    case Ver of 
         VerTM -> NewVars = dict:store(Name, {Ver+1, Value}, 
                                       Vars),
                  {true, NewVars} ;
         _     -> {false, Vars}
    end.

Composing transactions

Side-effects