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
a local clone.
core.sync.mutex
The mutex module provides a primitive for maintaining mutually exclusive
access.
License:
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 and CRITICAL_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 @trusted 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(Objectobj
); - 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 voidlock
();
final nothrow @nogc @trusted voidlock_nothrow
(this Q)()
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
in nothrow @nogc code. - @trusted void
unlock
();
shared @trusted voidunlock
();
final nothrow @nogc @trusted voidunlock_nothrow
(this Q)()
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
in nothrow @nogc code. - @trusted bool
tryLock
();
shared @trusted booltryLock
();
final nothrow @nogc @trusted booltryLock_nothrow
(this Q)()
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
in nothrow @nogc code.
Copyright © 1999-2024 by the D Language Foundation | Page generated by
Ddoc on Wed Dec 18 08:52:19 2024