www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is this should work?

reply markov <markov my.com> writes:
void test(string line){
...
};


void main(){
   string[] list;
   foreach (line; list)
     new Thread({test(line);}).start();
...
}
Oct 16 2016
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Oct 16 2016
parent reply markov <markov my.com> writes:
Thanks.

So something like this would be helpful in core.thread?

void startThread(alias fun, P...)(P p){
     new Thread({fun(p);}).start();
}
Oct 17 2016
parent Daniel Kozak via Digitalmars-d-learn <digitalmars-d-learn puremagic.com> writes:
Dne 17.10.2016 v 11:56 markov via Digitalmars-d-learn napsal(a):

 Thanks.

 So something like this would be helpful in core.thread?

 void startThread(alias fun, P...)(P p){
     new Thread({fun(p);}).start();
 }
or without delegate import std.stdio; import core.thread; void fun(alias a, alias msg)() { writefln("Hello number %d from %s", a, msg); } void main() { int a = 7; string msg = "main"; auto thr = new Thread(&fun!(a, msg)).start; thr.join; }
Oct 17 2016