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 // Platform independent code will include this header file which pulls
13 // the platfrom specific specializations using platform macros.
14 //
15 // The platform specific specializations should define a class by name
16 // Mutex with non-static methods having the following signature:
17 //
18 // MutexError lock();
19 // MutexError trylock();
20 // MutexError timedlock(...);
21 // MutexError unlock();
22 // MutexError reset(); // Used to reset inconsistent robust mutexes.
23 //
24 // Apart from the above non-static methods, the specializations should
25 // also provide few static methods with the following signature:
26 //
27 // static MutexError init(mtx_t *);
28 // static MutexError destroy(mtx_t *);
29 //
30 // All of the static and non-static methods should ideally be implemented
31 // as inline functions so that implementations of public functions can
32 // call them without a function call overhead.
33 //
34 // Another point to keep in mind that is that the libc internally needs a
35 // few global locks. So, to avoid static initialization order fiasco, we
36 // want the constructors of the Mutex classes to be constexprs.
37 
38 #ifdef __unix__
39 #include "linux/mutex.h"
40 #endif // __unix__
41 
42 namespace __llvm_libc {
43 
44 // An RAII class for easy locking and unlocking of mutexes.
45 class MutexLock {
46   Mutex *mutex;
47 
48 public:
MutexLock(Mutex * m)49   explicit MutexLock(Mutex *m) : mutex(m) { mutex->lock(); }
50 
~MutexLock()51   ~MutexLock() { mutex->unlock(); }
52 };
53 
54 } // namespace __llvm_libc
55 
56 #endif // LLVM_LIBC_SRC_SUPPORT_THREAD_MUTEX_H
57