1 /** 2 POSIX Implementation for nulib.threading.internal.mutex 3 4 Copyright: 5 Copyright © 2025, Kitsunebi Games 6 Copyright © 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.posix.threading.mutex; 12 import nulib.threading.internal.mutex; 13 import nulib.posix.pthread; 14 import numem; 15 16 version (OSX) 17 version = Darwin; 18 else version (iOS) 19 version = Darwin; 20 else version (TVOS) 21 version = Darwin; 22 else version (WatchOS) 23 version = Darwin; 24 else version (VisionOS) 25 version = Darwin; 26 27 /** 28 Native implementation of a mutually exclusive lock. 29 */ 30 class PosixMutex : NativeMutex { 31 private: 32 @nogc: 33 pthread_mutex_t handle_; 34 35 public: 36 37 ~this() nothrow { 38 auto rc = pthread_mutex_destroy(&handle_); 39 assert(!rc, "Failed to destroy mutex!"); 40 } 41 42 this() nothrow { 43 pthread_mutexattr_t attr = void; 44 auto rc = pthread_mutexattr_init(&attr); 45 assert(!rc, "Failed to create mutex!"); 46 47 if (!rc) { 48 rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); 49 assert(!rc, "Failed to create mutex!"); 50 51 rc = pthread_mutex_init(&handle_, &attr); 52 assert(!rc, "Failed to create mutex!"); 53 } 54 55 rc = pthread_mutexattr_destroy(&attr); 56 assert(!rc, "Failed to create mutex!"); 57 } 58 59 /** 60 Increments the internal lock counter. 61 */ 62 override 63 void lock() nothrow @trusted { 64 if (pthread_mutex_lock(&handle_) == 0) 65 return; 66 67 assert(0, "Failed to lock mutex!"); 68 } 69 70 /** 71 Tries to increment the internal lock counter. 72 73 Returns: 74 $(D true) if the mutex was locked, 75 $(D false) otherwise. 76 */ 77 override 78 bool tryLock() nothrow @trusted { 79 return pthread_mutex_trylock(&handle_) == 0; 80 } 81 82 /** 83 Decrements the internal lock counter, 84 If the counter reaches 0, the lock is released. 85 */ 86 override 87 void unlock() nothrow @trusted { 88 if (pthread_mutex_unlock(&handle_) == 0) 89 return; 90 91 assert(0, "Failed to unlock mutex!"); 92 } 93 } 94 95 extern(C) export 96 NativeMutex _nu_mutex_new() @trusted @nogc nothrow { 97 return nogc_new!PosixMutex(); 98 } 99 100 // 101 // BINDINGS 102 // 103 version(Darwin) { 104 105 } else version(Posix) { 106 107 }