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.

  1. auto ref initOnce(typeof(var) init)
  2. auto ref initOnce(typeof(var) init, Mutex mutex)
  3. auto ref initOnce(typeof(var) init, Mutex mutex)
    ref
    initOnce
    (
    alias var
    )
    (
    lazy typeof(var) init
    ,
    Mutex mutex
    )

Parameters

var

The variable to initialize

init typeof(var)

The lazy initializer value

mutex Mutex

A mutex to prevent race conditions

Return Value

Type: auto ref

A reference to the initialized variable

Examples

Use a separate mutex when init blocks on another thread that might also call initOnce.

import core.sync.mutex : Mutex;

static shared bool varA, varB;
static shared Mutex m;
m = new shared 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);

Meta