Whitch can replace std::bind/boost::bind ?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Mar 18 10:31:11 PDT 2016
On 03/18/2016 09:14 AM, Dsby wrote:
> On Friday, 18 March 2016 at 11:09:37 UTC, Atila Neves wrote:
>> On Friday, 18 March 2016 at 10:50:34 UTC, 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.
>>
>> I would suggest not using Thread directly:
>>
>> foreach(i; 0..4) {
>> auto tid = spawn(&listRun, i); //from std.concurrency
>> _tid[i] = tid;
>> }
>>
>> Atila
>
>
> the listrun is in class. it is a delegate,it is not a function.
Here is one that puts 'shared' in a lot of places:
import std.stdio;
import std.concurrency;
class C {
int i;
this (int i) shared {
this.i = i;
}
void listRun() shared {
writeln("listRun for ", i);
}
}
void worker(shared(C) c) {
c.listRun();
}
void main() {
Tid[4] _tid;
foreach(i; 0..4) {
auto c = new shared(C)(i);
auto tid = spawn(&worker, c);
_tid[i] = tid;
}
}
Here is an equivalent that casts to and from 'shared' before and after
the thread call:
import std.stdio;
import std.concurrency;
class C {
int i;
this (int i) {
this.i = i;
}
void listRun() {
writeln("listRun for ", i);
}
}
void worker(shared(C) c_shared) {
auto c = cast(C)c_shared;
c.listRun();
}
void main() {
Tid[4] _tid;
foreach(i; 0..4) {
auto c = new C(i);
auto c_shared = cast(shared(C))c;
auto tid = spawn(&worker, c_shared);
_tid[i] = tid;
}
}
Ali
More information about the Digitalmars-d-learn
mailing list