WPILibC++  unspecified
priority_mutex.h
1 /*----------------------------------------------------------------------------*/
2 /* Copyright (c) 2016-2018 FIRST. 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 #ifdef __linux__
12 #include <pthread.h>
13 #endif
14 
15 #include <mutex>
16 
17 namespace wpi {
18 
19 #ifdef __linux__
20 
21 #define WPI_HAVE_PRIORITY_MUTEX 1
22 
23 class priority_recursive_mutex {
24  public:
25  typedef pthread_mutex_t* native_handle_type;
26 
27  constexpr priority_recursive_mutex() noexcept = default;
28  priority_recursive_mutex(const priority_recursive_mutex&) = delete;
29  priority_recursive_mutex& operator=(const priority_recursive_mutex&) = delete;
30 
31  // Lock the mutex, blocking until it's available.
32  void lock() { pthread_mutex_lock(&m_mutex); }
33 
34  // Unlock the mutex.
35  void unlock() { pthread_mutex_unlock(&m_mutex); }
36 
37  // Tries to lock the mutex.
38  bool try_lock() noexcept { return !pthread_mutex_trylock(&m_mutex); }
39 
40  pthread_mutex_t* native_handle() { return &m_mutex; }
41 
42  private:
43 // Do the equivalent of setting PTHREAD_PRIO_INHERIT and
44 // PTHREAD_MUTEX_RECURSIVE_NP.
45 #ifdef __PTHREAD_MUTEX_HAVE_PREV
46  pthread_mutex_t m_mutex = {
47  {0, 0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, __PTHREAD_SPINS, {0, 0}}};
48 #else
49  pthread_mutex_t m_mutex = {
50  {0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, {__PTHREAD_SPINS}}};
51 #endif
52 };
53 
54 class priority_mutex {
55  public:
56  typedef pthread_mutex_t* native_handle_type;
57 
58  constexpr priority_mutex() noexcept = default;
59  priority_mutex(const priority_mutex&) = delete;
60  priority_mutex& operator=(const priority_mutex&) = delete;
61 
62  // Lock the mutex, blocking until it's available.
63  void lock() { pthread_mutex_lock(&m_mutex); }
64 
65  // Unlock the mutex.
66  void unlock() { pthread_mutex_unlock(&m_mutex); }
67 
68  // Tries to lock the mutex.
69  bool try_lock() noexcept { return !pthread_mutex_trylock(&m_mutex); }
70 
71  pthread_mutex_t* native_handle() { return &m_mutex; }
72 
73  private:
74 // Do the equivalent of setting PTHREAD_PRIO_INHERIT.
75 #ifdef __PTHREAD_MUTEX_HAVE_PREV
76  pthread_mutex_t m_mutex = {{0, 0, 0, 0, 0x20, __PTHREAD_SPINS, {0, 0}}};
77 #else
78  pthread_mutex_t m_mutex = {{0, 0, 0, 0x20, 0, {__PTHREAD_SPINS}}};
79 #endif
80 };
81 
82 #endif // __linux__
83 
84 } // namespace wpi
Definition: SocketError.cpp:17