Is this should work?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Oct 16 18:58:18 PDT 2016


On 10/16/2016 03:22 PM, markov wrote:
>
> void test(string line){
> ...
> };
>
>
> void main(){
>   string[] list;
>   foreach (line; list)
>     new Thread({test(line);}).start();
> ...
> }
>

It works in an unexpected way: In D, all those threads would close over 
the same 'line' loop variable, which happens to point to the last 
string, so they all see the last string:

import std.stdio;
import core.thread;

void test(size_t i, string line){
     writefln("Thread %s: %s", i, line);
}

void main(){
     string[] list = [ "hello", "world" ];
     foreach (i, line; list)
         new Thread({test(i, line);}).start();
}

Prints:

Thread 1: world    // <-- Expected 0 and "hello"
Thread 1: world

What needs to happen is to give the thread separate variables. An easy 
solution is to start the thread with the arguments of a function:

     foreach (i, line; list) {
         void startThread(size_t j, string l) {
             new Thread({test(j, l);}).start();    // <-- Uses function
                                                   //     arguments
         }
         startThread(i, line);
     }

I happened to define a nested function. You can define it anywhere else.

Ali



More information about the Digitalmars-d-learn mailing list