Mutex

This class represents a general purpose, recursive mutex.

Implemented using pthread_mutex on Posix and CRITICAL_SECTION on Windows.

Constructors

this
this()

Initializes a mutex object.

this
this(Object obj)

Initializes a mutex object and sets it as the monitor for obj.

Destructor

A destructor is present on this object, but not explicitly documented in the source.

Members

Functions

lock
void lock()
lock_nothrow
void lock_nothrow()

If this lock is not already held by the caller, the lock is acquired, then the internal counter is incremented by one.

tryLock
bool tryLock()
tryLock_nothrow
bool tryLock_nothrow()

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.

unlock
void unlock()
unlock_nothrow
void unlock_nothrow()

Decrements the internal lock count by one. If this brings the count to zero, the lock is released.

Examples

1 import core.thread : Thread;
2 
3 class Resource
4 {
5     Mutex mtx;
6     int cargo;
7 
8     this() shared @safe nothrow
9     {
10         mtx = new shared Mutex();
11         cargo = 42;
12     }
13 
14     void useResource() shared @safe nothrow @nogc
15     {
16         mtx.lock_nothrow();
17         (cast() cargo) += 1;
18         mtx.unlock_nothrow();
19     }
20 }
21 
22 shared Resource res = new shared Resource();
23 
24 auto otherThread = new Thread(
25 {
26     foreach (i; 0 .. 10000)
27         res.useResource();
28 }).start();
29 
30 foreach (i; 0 .. 10000)
31     res.useResource();
32 
33 otherThread.join();
34 
35 assert (res.cargo == 20042);
Suggestion Box / Bug Report