Search⌘ K
AI Features

static this() and Atomic Operations

Explore how to properly initialize module variables across threads using shared static this and static ~this in D. Understand atomic operations like atomicOp and compare-and-swap (cas) to manage concurrency without locks, ensuring thread-safe updates and avoiding race conditions in your D programs.

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:

D
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 ...