View source code
Display the source code in std/concurrency.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

std.concurrency.initOnce - multiple declarations

Function initOnce

Initializes var with the lazy init value in a thread-safe manner.

ref auto initOnce(alias var) (
  lazy typeof(var) init
);

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.

Parameters

NameDescription
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()
    {
        __gshared MySingleton inst;
        return initOnce!inst(new MySingleton);
    }
}

assert(MySingleton.instance !is null);

Function initOnce

Same as above, but takes a separate mutex instead of sharing one among all initOnce instances.

ref auto initOnce(alias var) (
  lazy typeof(var) init,
  shared Mutex mutex
);

ref auto initOnce(alias var) (
  lazy typeof(var) init,
  Mutex mutex
);

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.

Parameters

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

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);
writeln(varA); // true
writeln(varB); // true

Authors

Sean Kelly, Alex Rønne Petersen, Martin Nowak

License

Boost License 1.0.