core.sync.mutex
The mutex module provides a primitive for maintaining mutually exclusive access.
- License:
- Boost License 1.0
- Authors:
- Sean Kelly
- Source
- core/sync/mutex.d
- class Mutex: object.Object.Monitor;
-
This class represents a general purpose, recursive mutex.
Implemented using
pthread_mutex
on Posix andCRITICAL_SECTION
on Windows.- Examples:
-
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(); (cast() cargo) += 1; 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);
- nothrow @nogc @trusted this();
shared nothrow @nogc @trusted this(); -
Initializes a mutex object.
- nothrow @nogc @trusted this(Object obj);
shared nothrow @nogc @trusted this(Object obj); -
Initializes a mutex object and sets it as the monitor for
obj
.- In
-
obj
must not already have a monitor.
- @trusted void lock();
shared @trusted void lock();
final nothrow @nogc @trusted void lock_nothrow(this Q)()
Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); -
If this lock is not already held by the caller, the lock is acquired, then the internal counter is incremented by one.
- Note
-
Mutex.lock
does not throw, but a class derived from Mutex can throw. Uselock_nothrow
innothrow @nogc
code.
- @trusted void unlock();
shared @trusted void unlock();
final nothrow @nogc @trusted void unlock_nothrow(this Q)()
Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); -
Decrements the internal lock count by one. If this brings the count to zero, the lock is released.
- Note
-
Mutex.unlock
does not throw, but a class derived from Mutex can throw. Useunlock_nothrow
innothrow @nogc
code.
- @trusted bool tryLock();
shared @trusted bool tryLock();
final nothrow @nogc @trusted bool tryLock_nothrow(this Q)()
Constraints: if (is(Q == Mutex) || is(Q == shared(Mutex))); -
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.
- Returns:
- true if the lock was acquired and false if not.
- Note
-
Mutex.tryLock
does not throw, but a class derived from Mutex can throw. UsetryLock_nothrow
innothrow @nogc
code.
© 1999–2021 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/phobos/core_sync_mutex.html