| Thread overview | ||||||
|---|---|---|---|---|---|---|
|
October 16, 2016 Is this should work? | ||||
|---|---|---|---|---|
| ||||
void test(string line){
...
};
void main(){
string[] list;
foreach (line; list)
new Thread({test(line);}).start();
...
}
| ||||
October 16, 2016 Re: Is this should work? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to markov | 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
| |||
October 17, 2016 Re: Is this should work? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | Thanks.
So something like this would be helpful in core.thread?
void startThread(alias fun, P...)(P p){
new Thread({fun(p);}).start();
}
| |||
October 17, 2016 Re: Is this should work? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to markov | 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;
}
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply