Order of Static Construction

Neia Neutuladh neia at ikeran.org
Fri Jan 4 16:48:26 UTC 2019


On Fri, 04 Jan 2019 13:27:29 +0000, Dru wrote:
> from the spec:
> "Shared static constructors on all modules are run before any non-shared
> static constructors."
> 
> Is there a specific reason, or is it just for simplicity?
> 
> There could be a situation where a shared ctor depends on a thread local
> variable.
> Preferably, the variable is only initialized in a non-shared ctor.

This part of the spec isn't entirely correct. Consider:

---
shared static this()
{
  writeln("shared ctor start");
  new Thread({}).start;
  Thread.sleep(10.seconds);
  writeln("shared ctor done");
}
static this()
{
  writeln("non-shared ctor");
}
---

This prints:

shared ctor start
non-shared ctor
shared ctor done

In order to fix this, the compiler would have to defer running threads 
until static constructors finish. But a static constructor that starts a 
thread could easily be waiting for it to finish and yield a result before 
continuing, leading to deadlocks.

In https://issues.dlang.org/show_bug.cgi?id=19492, I suggested a warning 
or error instead of trying to do the right thing.


More information about the Digitalmars-d mailing list