...

/

static this() and Atomic Operations

static this() and Atomic Operations

Learn how shared static this() is used for single initialization and shared static ~this() can be used for single finalization. Also get an introduction to atomic operations in this lesson.

static this() and static ~this()

We have already discussed how static this() can be used for initializing modules, including their variables. Because data is thread-local by default, static this() must be executed by every thread so that module-level variables are initialized for all threads:

Press + to interact
import std.stdio;
import std.concurrency;
import core.thread;
static this() {
writeln("executing static this()");
}
void worker() {
}
void main() {
spawn(&worker);
thread_joinAll();
}

The static this() block above would be executed once for the main thread and once for the worker thread.

This would cause problems for shared module variables because initializing a variable more than once would be wrong, especially in concurrency due to race conditions. This also applies to immutable variables because they are implicitly shared. The solution is to use ...