WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
priority_mutex.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) FIRST 2016. All Rights Reserved. */
3 /* Open Source Software - may be modified and shared by FRC teams. The code */
4 /* must be accompanied by the FIRST BSD license file in the root directory of */
5 /* the project. */
6 /*----------------------------------------------------------------------------*/
7 
8 #pragma once
9 
10 // Allows usage with std::lock_guard without including <mutex> separately
11 #include <mutex>
12 
13 #ifdef FRC_SIMULATOR
14 // We do not want to use pthreads if in the simulator; however, in the
15 // simulator, we do not care about priority inversion.
16 typedef std::mutex priority_mutex;
17 typedef std::recursive_mutex priority_recursive_mutex;
18 #else // Covers rest of file.
19 
20 #include <pthread.h>
21 
23  public:
24  typedef pthread_mutex_t* native_handle_type;
25 
26  constexpr priority_recursive_mutex() noexcept = default;
28  priority_recursive_mutex& operator=(const priority_recursive_mutex&) = delete;
29 
30  // Lock the mutex, blocking until it's available.
31  void lock();
32 
33  // Unlock the mutex.
34  void unlock();
35 
36  // Tries to lock the mutex.
37  bool try_lock() noexcept;
38 
39  pthread_mutex_t* native_handle();
40 
41  private:
42 // Do the equivalent of setting PTHREAD_PRIO_INHERIT and
43 // PTHREAD_MUTEX_RECURSIVE_NP.
44 #if __WORDSIZE == 64
45  pthread_mutex_t m_mutex = {
46  {0, 0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, 0, {0, 0}}};
47 #else
48  pthread_mutex_t m_mutex = {
49  {0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, {0}}};
50 #endif
51 };
52 
54  public:
55  typedef pthread_mutex_t* native_handle_type;
56 
57  constexpr priority_mutex() noexcept = default;
58  priority_mutex(const priority_mutex&) = delete;
59  priority_mutex& operator=(const priority_mutex&) = delete;
60 
61  // Lock the mutex, blocking until it's available.
62  void lock();
63 
64  // Unlock the mutex.
65  void unlock();
66 
67  // Tries to lock the mutex.
68  bool try_lock() noexcept;
69 
70  pthread_mutex_t* native_handle();
71 
72  private:
73 // Do the equivalent of setting PTHREAD_PRIO_INHERIT.
74 #if __WORDSIZE == 64
75  pthread_mutex_t m_mutex = {{0, 0, 0, 0, 0x20, 0, 0, {0, 0}}};
76 #else
77  pthread_mutex_t m_mutex = {{0, 0, 0, 0x20, 0, {0}}};
78 #endif
79 };
80 
81 #endif // FRC_SIMULATOR
Definition: priority_mutex.h:22
Definition: priority_mutex.h:53