1 //===--- A platform independent abstraction layer for mutexes ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_LIBC_SRC_SUPPORT_THREAD_MUTEX_H 10 #define LLVM_LIBC_SRC_SUPPORT_THREAD_MUTEX_H 11 12 namespace __llvm_libc { 13 14 enum class MutexError : int { 15 NONE, 16 BUSY, 17 TIMEOUT, 18 UNLOCK_WITHOUT_LOCK, 19 BAD_LOCK_STATE, 20 }; 21 22 } // namespace __llvm_libc 23 24 // Platform independent code will include this header file which pulls 25 // the platfrom specific specializations using platform macros. 26 // 27 // The platform specific specializations should define a class by name 28 // Mutex with non-static methods having the following signature: 29 // 30 // MutexError lock(); 31 // MutexError trylock(); 32 // MutexError timedlock(...); 33 // MutexError unlock(); 34 // MutexError reset(); // Used to reset inconsistent robust mutexes. 35 // 36 // Apart from the above non-static methods, the specializations should 37 // also provide few static methods with the following signature: 38 // 39 // static MutexError init(mtx_t *); 40 // static MutexError destroy(mtx_t *); 41 // 42 // All of the static and non-static methods should ideally be implemented 43 // as inline functions so that implementations of public functions can 44 // call them without a function call overhead. 45 // 46 // Another point to keep in mind that is that the libc internally needs a 47 // few global locks. So, to avoid static initialization order fiasco, we 48 // want the constructors of the Mutex classes to be constexprs. 49 50 #ifdef __unix__ 51 #include "linux/mutex.h" 52 #endif // __unix__ 53 54 namespace __llvm_libc { 55 56 // An RAII class for easy locking and unlocking of mutexes. 57 class MutexLock { 58 Mutex *mutex; 59 60 public: 61 explicit MutexLock(Mutex *m) : mutex(m) { mutex->lock(); } 62 63 ~MutexLock() { mutex->unlock(); } 64 }; 65 66 } // namespace __llvm_libc 67 68 #endif // LLVM_LIBC_SRC_SUPPORT_THREAD_MUTEX_H 69