spawn and wait

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 2 21:51:07 PDT 2014


On 07/02/2014 08:29 PM, Puming wrote:

 > I want to spawn several similar tasks and then wait for all of them to
 > complete to go on do some other things

If you don't care about account for each of them individually, 
core.thread.thread_joinAll would work. The following program starts two 
waves of threads and waits for both of the waves to complete:

import std.stdio;
import std.concurrency;
import core.thread;

void foo(Duration duration)
{
     writefln("Working for %s", duration);
     Thread.sleep(duration);
}

void spawnThreads(size_t count)
{
     foreach (i; 0 .. count) {
         spawn(&foo, (i + 1).seconds);
     }
     writefln("Started %s workers", count);
}

void main()
{
     spawnThreads(2);
     writefln("Waiting for all to finish");
     thread_joinAll();

     spawnThreads(3);
     writefln("Waiting for all to finish");
     thread_joinAll();
}

Ali



More information about the Digitalmars-d-learn mailing list