digitalmars.D.learn - Is this should work?
- markov (9/9) Oct 16 2016 void test(string line){
- =?UTF-8?Q?Ali_=c3=87ehreli?= (28/37) Oct 16 2016 It works in an unexpected way: In D, all those threads would close over
- markov (5/5) Oct 17 2016 Thanks.
- Daniel Kozak via Digitalmars-d-learn (15/20) Oct 17 2016 or without delegate
void test(string line){
...
};
void main(){
string[] list;
foreach (line; list)
new Thread({test(line);}).start();
...
}
Oct 16 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
Oct 16 2016
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
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








Daniel Kozak via Digitalmars-d-learn <digitalmars-d-learn puremagic.com>