On Friday, 18 March 2016 at 17:24:27 UTC, Ali Çehreli wrote:
On 03/18/2016 03:50 AM, Dsby wrote:
foreach (i ; 0..4) {
auto th = new Thread(delegate(){listRun(i);});//this is
erro
_thread[i]= th;
th.start();
}
void listRun(int i)
{
writeln("i = ", i); // the value is not(0,1,2,3), it all
is 2.
}
I want to know how to use it like std::bind.
A workaround is an intermediate function that returns the
delegate:
import std.stdio;
import core.thread;
void listRun(int i)
{
writeln("i = ", i); // the value is not(0,1,2,3), it all
is 2.
}
auto makeClosure(int i) {
return delegate(){listRun(i);};
}
void main() {
Thread[4] _thread;
foreach (i ; 0..4) {
auto th = new Thread(makeClosure(i));
_thread[i]= th;
th.start();
}
}
Prints different values:
i = 1
i = 0
i = 2
i = 3
Ali
Thanks for your mind.
i write the bind function:
import std.stdio;
import core.thread;
import std.functional;
class AA
{
void show(int i)
{
writeln("i = ", i); // the value is not(0,1,2,3), it all
is 2.
}
}
void listRun(int i)
{
writeln("i = ", i);
}
void main() {
Thread[4] _thread;
Thread[4] _thread2;
AA a = new AA();
foreach (i ; 0..4) {
auto th = new Thread(bindDg(&a.show,i));
_thread[i]= th;
auto th2 = new Thread(bindFun!listRun(i + 10));
_thread2[i]= th2;
}
foreach(i;0..4)
{
_thread[i].start();
}
foreach(i;0..4)
{
_thread2[i].start();
}
}
auto bindDg(T, Args...)(T fun,Args args) if (is(T == delegate) ||
is(T == function))
{
return delegate(){return fun(forward!args);};
}
auto bindFun(alias Fun,Args...)(Args args) {
return delegate(){return Fun(forward!args);};
}
my value is :
i = 2
i = 0
i = 3
i = 11
i = 13
i = 10
i = 12
i = 1