Closure/Stack-to-Heap Semantics

dsimcha dsimcha at yahoo.com
Wed Sep 24 20:45:32 PDT 2008


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?



More information about the Digitalmars-d mailing list