www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - std.concurrency and module constructors

reply "japplegame" <japplegame gmail.com> writes:
OS: Windows 7 64bit
Compiler: DMD32 D Compiler v2.059

Using spawn in module constructor causes very strange behavior.

import std.concurrency;
import std.stdio;
void main() {
}
void worker() {
   receiveOnly!OwnerTerminated;
}
static this() {
   writeln("module constructor");
   spawn(&worker);
}
static ~this() {
   writeln("module destructor");
}

prints in console:

module constructor
module destructor
module constructor
module destructor
module constructor
module constructor
module constructor
module constructor
module constructor
...
May 11 2012
parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On Fri, 11 May 2012 14:56:03 +0200, japplegame <japplegame gmail.com>  
wrote:

 OS: Windows 7 64bit
 Compiler: DMD32 D Compiler v2.059

 Using spawn in module constructor causes very strange behavior.

 import std.concurrency;
 import std.stdio;
 void main() {
 }
 void worker() {
    receiveOnly!OwnerTerminated;
 }
 static this() {
    writeln("module constructor");
    spawn(&worker);
 }
 static ~this() {
    writeln("module destructor");
 }

 prints in console:

 module constructor
 module destructor
 module constructor
 module destructor
 module constructor
 module constructor
 module constructor
 module constructor
 module constructor
 ...
Indeed it does. spawn creates a new thread, which has to construct its own modules (things are thread-local in D, after all). Doing so calls spawn again, which creates a new thread...
May 11 2012
parent reply "japplegame" <japplegame gmail.com> writes:
Thank you.

Solution is:
shared static this() {
...
}

or avoid any global things :)
May 11 2012
parent sclytrack <sclytrack iq87.fr> writes:
On 05/11/2012 03:44 PM, japplegame wrote:
 Thank you.

 Solution is:
 shared static this() {
 ...
 }

 or avoid any global things :)
And I learned something new today. :-)
May 11 2012