WPILibC++  unspecified
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Pages
priority_mutex.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) FIRST 2016-2017. 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 #if defined(FRC_SIMULATOR) || defined(_WIN32)
14 namespace hal {
15 // We do not want to use pthreads if in the simulator; however, in the
16 // simulator, we do not care about priority inversion.
17 typedef std::mutex priority_mutex;
18 typedef std::recursive_mutex priority_recursive_mutex;
19 } // namespace hal
20 #else // Covers rest of file.
21 
22 #include <pthread.h>
23 
24 namespace hal {
25 
27  public:
28  typedef pthread_mutex_t* native_handle_type;
29 
30  constexpr priority_recursive_mutex() noexcept = default;
32  priority_recursive_mutex& operator=(const priority_recursive_mutex&) = delete;
33 
34  // Lock the mutex, blocking until it's available.
35  void lock();
36 
37  // Unlock the mutex.
38  void unlock();
39 
40  // Tries to lock the mutex.
41  bool try_lock() noexcept;
42 
43  pthread_mutex_t* native_handle();
44 
45  private:
46 // Do the equivalent of setting PTHREAD_PRIO_INHERIT and
47 // PTHREAD_MUTEX_RECURSIVE_NP.
48 #if __WORDSIZE == 64
49  pthread_mutex_t m_mutex = {
50  {0, 0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, 0, {0, 0}}};
51 #else
52  pthread_mutex_t m_mutex = {
53  {0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, {0}}};
54 #endif
55 };
56 
58  public:
59  typedef pthread_mutex_t* native_handle_type;
60 
61  constexpr priority_mutex() noexcept = default;
62  priority_mutex(const priority_mutex&) = delete;
63  priority_mutex& operator=(const priority_mutex&) = delete;
64 
65  // Lock the mutex, blocking until it's available.
66  void lock();
67 
68  // Unlock the mutex.
69  void unlock();
70 
71  // Tries to lock the mutex.
72  bool try_lock() noexcept;
73 
74  pthread_mutex_t* native_handle();
75 
76  private:
77 // Do the equivalent of setting PTHREAD_PRIO_INHERIT.
78 #if __WORDSIZE == 64
79  pthread_mutex_t m_mutex = {{0, 0, 0, 0, 0x20, 0, 0, {0, 0}}};
80 #else
81  pthread_mutex_t m_mutex = {{0, 0, 0, 0x20, 0, {0}}};
82 #endif
83 };
84 } // namespace hal
85 
86 #endif // FRC_SIMULATOR
87 
88 // For backwards compatibility
89 #ifndef NAMESPACED_PRIORITY
90 using priority_mutex = hal::priority_mutex; // NOLINT
92 #endif
Definition: priority_mutex.h:26
Definition: priority_mutex.h:57