Are spawn'ed threads waited automatically?

Ali Çehreli acehreli at yahoo.com
Mon Jun 6 11:09:25 PDT 2011


First, the answer may be as simple as "use core.thread.thread_joinAll". 
Is that the proper way of waiting for all threads?

Second, my question may not be a valid example as starting a thread 
without communicating with it may be under the umbrella of 
parallelization. Maybe in concurrency, threads communicate with each 
other so that the following situation should not occur in practice.

Third is my question: :) If I spawn a single thread in main, the single 
thread seems to run to completion.

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

void foo()
{
     foreach (i; 0 .. 5) {
         Thread.sleep(dur!"msecs"(500));
         writeln(i, " foo");
     }
}

void main()
{
     spawn(&foo);
     writeln("main done");
}

I get all of foo's output after "main done":

main done
0 foo
1 foo
2 foo
3 foo
4 foo

If I introduce an intermediate thread that spawns the foo thread, now 
foo sometimes terminates early:

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

void foo()
{
     foreach (i; 0 .. 5) {
         Thread.sleep(dur!"msecs"(500));
         writeln(i, " foo");
     }
}

void intermediate()
{
     spawn(&foo);
     writeln("intermediate done");
}

void main()
{
     spawn(&intermediate);
     writeln("main done");
}

The output is inconsistent. Sometimes there is nothing from foo:

main done
intermediate done

Sometimes it runs fully:

main done
intermediate done
0 foo
1 foo
2 foo
3 foo
4 foo

Is the inconsistency a bug or a natural consequence of something? :) 
(Perhaps even the first example that seems to run correctly just has a 
higher probability of showing this behavior.)

I am aware of thread_joinAll(). Is that the recommended way of waiting 
for all threads?

Thank you,
Ali


More information about the Digitalmars-d-learn mailing list