Closure/Stack-to-Heap Semantics
downs
default_357-line at yahoo.de
Thu Sep 25 04:13:02 PDT 2008
dsimcha wrote:
> If I write a loop, and want to submit each iteration of that loop to its own
> thread, or to a thread pool or something, how do I get D to copy the current
> stack frame to the heap each time I use the delegate? For example:
>
> import std.thread, std.stdio, std.c.time;
>
> void main() {
> Thread[] myThreads = new Thread[100];
> foreach(i; 0..100) {
> auto T = new Thread({
> sleep(1); //Give i time to be incremented to 100.
> writeln(i);
> return 0;
> });
> T.start;
> myThreads[i] = T;
> }
> foreach(T; myThreads) {
> T.wait;
> }
> }
>
> This program prints out all 100's because by the time each thread is done
> sleeping, i = 100. How do I make D copy the stack context each time I submit
> a delegate to a thread, in similar fashion to a closure?
This is how I'd do it with tools/1.0:
void main() {
auto tp = new Threadpool(100);
auto sem = new Semaphore;
foreach (i; Range[0..100].endIncl) {
tp.addTask(i /apply/ (int i) {
sleep(1);
writefln(i);
sem.release;
});
}
foreach (i; Range[0..100].endIncl)
sem.acquire;
}
(Untested)
More information about the Digitalmars-d
mailing list