roxen.lists.pike.general

Subject Author Date
Re: thread and lambda zenothing <zenothing[at]hotmail[dot]com> 22-03-2009
for(int i=0;i<100;i++){
    Thread.Thread(lambda(){ sleep(3);write("%d\n",i);});
}

When the body of lambda(){} is large, the programmer may forgot that the var 
i is outside the lambda function.

The guy may wish write "0\n" "1\n" ... "100\n" randomly, but he will got 
"100\n"*100.

If there are something need to write, the guy may also forget that is 
outside the function and forget to add a lock, for example:

int sum;
for(int i=0;i<100;i++){
    Thread.Thread(lambda(){
        /* too much code here, and take a long time to run */
        write("%d\n",i);
        sum+=i;
        /* too much code here too*/
    });
}

My problem is not "how to write correct code" but "how to avoid mistake"

--------------------------------------------------
From: "Mirar @ Pike  importm?te f?r mailinglistan"
<<6341[at]lyskom.lysator.liu.se>>
Sent: Sunday, March 22, 2009 7:00 PM
To: <<pike[at]roxen.com>>
Subject: thread and lambda

> Why is non-locked variables a problem? It seems to me it will only be
> a problem if several threads are going to write to the same variables
> in a non-atomic way.
>
> In your examples, the threads will only read the variables, and thus
> there isn't any problem or need for lock.
>
> Do you have a real-world example of a problem?
>
>