Sourcecore/sync/mutex.d
Mutex:object.Object.Monitor;import core.thread : Thread;class Resource{Mutex mtx;int cargo;this()shared @safenothrow { mtx =newsharedMutex(); cargo = 42; }void useResource()shared @trustednothrow @nogc { mtx.lock_nothrow(); (cast() cargo) += 1; mtx.unlock_nothrow(); }}shared Resource res =newshared Resource();auto otherThread =new Thread({foreach (i; 0 .. 10000) res.useResource();}).start();foreach (i; 0 .. 10000) res.useResource();otherThread.join();assert (res.cargo == 20042);
obj);obj) shared;obj.Inobj must not already have a monitor.
lock();lock() shared;lock_nothrow(this Q)()NoteMutex.lock does not throw, but a class derived from Mutex can throw. Uselock_nothrow innothrow @nogc code.
unlock();unlock() shared;unlock_nothrow(this Q)()NoteMutex.unlock does not throw, but a class derived from Mutex can throw. Useunlock_nothrow innothrow @nogc code.
tryLock();tryLock() shared;tryLock_nothrow(this Q)()NoteMutex.tryLock does not throw, but a class derived from Mutex can throw. UsetryLock_nothrow innothrow @nogc code.