The variable to initialize
The lazy initializer value
A mutex to prevent race conditions
A reference to the initialized variable
Use a separate mutex when init blocks on another thread that might also call initOnce.
1 import core.sync.mutex : Mutex; 2 3 static shared bool varA, varB; 4 static shared Mutex m; 5 m = new shared Mutex; 6 7 spawn({ 8 // use a different mutex for varB to avoid a dead-lock 9 initOnce!varB(true, m); 10 ownerTid.send(true); 11 }); 12 // init depends on the result of the spawned thread 13 initOnce!varA(receiveOnly!bool); 14 assert(varA == true); 15 assert(varB == true);
Same as above, but takes a separate mutex instead of sharing one among all initOnce instances.
This should be used to avoid dead-locks when the init expression waits for the result of another thread that might also call initOnce. Use with care.