1 /**
2     Mutually Exclusive Locks
3 
4     Copyright:
5         Copyright © 2023-2025, Kitsunebi Games
6         Copyright © 2023-2025, Inochi2D Project
7     
8     License:   $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9     Authors:   Luna Nielsen
10 */
11 module nulib.threading.mutex;
12 import nulib.threading.internal.mutex;
13 import numem;
14 
15 /**
16     A mutually exclusive lock.
17 */
18 class Mutex : NuObject {
19 private:
20 @nogc:
21     NativeMutex mutex_;
22 
23 public:
24 
25     /**
26         The native implementation defined handle of the mutex.
27     */
28     final @property NativeMutex nativeHandle() => mutex_;
29 
30     /// Destructor
31     ~this() {
32         nogc_delete(mutex_);
33     }
34 
35     /**
36         Constructs a new Mutex.
37     */
38     this() {
39         this.mutex_ = NativeMutex.create();
40         enforce(mutex_, "Mutex is not supported on this platform.");
41     }
42 
43     /**
44         Increments the internal lock counter.
45     */
46     void lock() nothrow @safe {
47         mutex_.lock();
48     }
49 
50     /**
51         Tries to increment the internal lock counter.
52 
53         Returns:
54             $(D true) if the mutex was locked,
55             $(D false) otherwise.
56     */
57     bool tryLock() nothrow @safe {
58         return mutex_.tryLock();
59     }
60 
61     /**
62         Decrements the internal lock counter,
63         If the counter reaches 0, the lock is released.
64     */
65     void unlock() nothrow @safe {
66         mutex_.unlock();
67     }
68 }
69 
70 @("lock and unlock")
71 unittest {
72     Mutex m = nogc_new!Mutex();
73     m.lock();
74     m.unlock();
75     nogc_delete(m);
76 }