The mutex
module provides a primitive for maintaining mutually exclusive access.
This class represents a general purpose, recursive mutex.
Implemented using pthread_mutex
on Posix and CRITICAL_SECTION
on Windows.
import core.thread : Thread; class Resource { Mutex mtx; int cargo; this() shared @safe nothrow { mtx = new shared Mutex(); cargo = 42; } void useResource() shared @safe nothrow @nogc { mtx.lock_nothrow(); cargo++; mtx.unlock_nothrow(); } } shared Resource res = new shared Resource(); auto otherThread = new Thread( { foreach (i; 0 .. 10000) res.useResource(); }).start(); foreach (i; 0 .. 10000) res.useResource(); otherThread.join(); assert (res.cargo == 20042);
Initializes a mutex object.
Initializes a mutex object and sets it as the monitor for obj
.
obj
must not already have a monitor.If this lock
is not already held by the caller, the lock
is acquired, then the internal counter is incremented by one.
Mutex.lock
does not throw, but a class derived from Mutex can throw. Use lock_nothrow
in nothrow @nogc
code.Decrements the internal lock count by one. If this brings the count to zero, the lock is released.
Mutex.unlock
does not throw, but a class derived from Mutex can throw. Use unlock_nothrow
in nothrow @nogc
code.If the lock is held by another caller, the method returns. Otherwise, the lock is acquired if it is not already held, and then the internal counter is incremented by one.
true
if the lock was acquired and false
if not. Mutex.tryLock
does not throw, but a class derived from Mutex can throw. Use tryLock_nothrow
in nothrow @nogc
code.
© 1999–2017 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/core_sync_mutex.html