>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*/
> });
>}
So, the problem is that you're using variables you thought were local,
but they aren't?
>My problem is not "how to write correct code" but "how to avoid mistake"
But I don't see how your proposal would solve that problem.
All non-local variables would be thread-shared if you're using threads
anywhere in the environment. A lambda isn't special. I'm not sure
where you would want the warning - in the use of lambdas with
out-of-scope variables that are given as argument to Thread.Thread()?
Should this give a warning to? Where?
int global_variable;
function f=lambda() { global_variable++; }
void myfunc() { Thread.Thread(f); }
this?
function g() { global_variable++; };
function f=g;
void myfunc() { Thread.Thread(f); }
And locks really doesn't have anything to do with the problem of
variables changing value outside the thread:
Thread.Mutex i_lock=Thread.Mutex();
object key=i_lock()->lock;
for(int i=0;i<100;i++){
Thread.Thread(lambda(){
object key=i_lock()->lock;
...i...
destruct(key);
})};
destruct(key);
or even
Thread.Mutex i_lock=Thread.Mutex();
for (int i=0; i<100; )
{
Thread.Thread(lambda(){
object key=i_lock()->lock;
...i...
destruct(key);
});
object key=i_lock()->lock;
i++;
destruct(key);
}
seems to solve the problem you mention.
Sorry if I'm confused...
|