[erlang-questions] how to scale into the cloud using process? example computing simple average

Ulf Wiger ulf.wiger@REDACTED
Tue May 26 09:24:50 CEST 2009


Kid Erlang wrote:
> 
> I try to write simple example with spawn.  I want to make simple average 
> of these numbers as example, but calculate in paralell so it can 
> automagically scale into the cloud!  Here is my program:
> 
> -module(averager).
> -compile(export_all).
> 
> paralell_average(List)->
>   N=0,lists:foreach(fun(X)-> spawn(fun()-> N+X end)end,List),N/length(List).
> 
> but it always returns 0.0 no mater what List is!  what am I doing wrong? 

When you spawn processes, they will have their own memory and
their own scope. The original process will have no idea what
they do unless they send a message back. In your program above,
the spawned processes add to N, but this has no effect whatsoever
on the original N on the heap of the parent process. Even if it
would, remember that the value of a variable cannot change.
You have declared that N=0, so N/length(List) can never be
anything other than 0 (within the scope of this function.)

Specifically, your spawned processes will begin life by executing
the given fun, which adds X to N, returning the value... in this
case to nothing, since there's no calling function to receive it.
Thus, the return value of the fun is discarded, and the process,
having no more work to perform, dies. Since it doesn't communicate
with anyone, and no other process is monitoring it, its death
goes unnoticed.

A function like parallel_average will not scale in this manner,
since the operation of spawning processes, lightweight as it may
be, is heavier than the operation of calculating X+N.

BR,
Ulf W
-- 
Ulf Wiger
CTO, Erlang Training & Consulting Ltd
http://www.erlang-consulting.com



More information about the erlang-questions mailing list