std.concurrency.init_once
- multiple declarations
- Function initOnce
- Function initOnce
Function initOnce
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.
Prototype
auto ref initOnce(alias var)( typeof(var) init, Mutex mutex );
Parameters
Name | Description |
---|---|
var | The variable to initialize |
init | The lazy initializer value |
mutex | A mutex to prevent race conditions |
Returns
A reference to the initialized variable
Example
Use a separate mutex
when init
blocks on another thread that might also call initOnce
.
static shared bool varA, varB; __gshared Mutex m; m = new Mutex; spawn({ // use a different mutex for varB to avoid a dead-lock initOnce!varB(true, m); ownerTid.send(true); }); // init depends on the result of the spawned thread initOnce!varA(receiveOnly!bool); assert(varA == true); assert(varB == true);
Function initOnce
Initializes var with the lazy init
value in a
thread-safe manner.
The implementation guarantees that all threads simultaneously calling
initOnce
with the same var argument block until var is
fully initialized. All side-effects of init
are globally visible
afterwards.
Prototype
auto ref initOnce(alias var)( typeof(var) init );
Parameters
Name | Description |
---|---|
var | The variable to initialize |
init | The lazy initializer value |
Returns
A reference to the initialized variable
Example
A typical use-case is to perform lazy but thread-safe initialization.
static class MySingleton { static MySingleton instance() { static __gshared MySingleton inst; return initOnce!inst(new MySingleton); } } assert(MySingleton.instance !is null);
Authors
Sean Kelly, Alex Rønne Petersen, Martin Nowak