WPILibC++ 2024.3.2
priority_mutex.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7// Allows usage with std::scoped_lock without including <mutex> separately
8#ifdef __linux__
9#include <pthread.h>
10#endif
11
12#include <mutex>
13
14namespace wpi {
15
16#if defined(__FRC_ROBORIO__) && !defined(WPI_USE_PRIORITY_MUTEX)
17#define WPI_USE_PRIORITY_MUTEX
18#endif
19
20#if defined(WPI_USE_PRIORITY_MUTEX) && defined(__linux__)
21
22#define WPI_HAVE_PRIORITY_MUTEX 1
23
24class priority_recursive_mutex {
25 public:
26 using native_handle_type = pthread_mutex_t*;
27
28 constexpr priority_recursive_mutex() noexcept = default;
29 priority_recursive_mutex(const priority_recursive_mutex&) = delete;
30 priority_recursive_mutex& operator=(const priority_recursive_mutex&) = delete;
31
32 // Lock the mutex, blocking until it's available.
33 void lock() { pthread_mutex_lock(&m_mutex); }
34
35 // Unlock the mutex.
36 void unlock() { pthread_mutex_unlock(&m_mutex); }
37
38 // Tries to lock the mutex.
39 bool try_lock() noexcept { return !pthread_mutex_trylock(&m_mutex); }
40
41 pthread_mutex_t* native_handle() { return &m_mutex; }
42
43 private:
44// Do the equivalent of setting PTHREAD_PRIO_INHERIT and
45// PTHREAD_MUTEX_RECURSIVE_NP.
46#ifdef __PTHREAD_MUTEX_HAVE_PREV
47 pthread_mutex_t m_mutex = {
48 {0, 0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, __PTHREAD_SPINS, {0, 0}}};
49#else
50 pthread_mutex_t m_mutex = {
51 {0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, {__PTHREAD_SPINS}}};
52#endif
53};
54
55class priority_mutex {
56 public:
57 using native_handle_type = pthread_mutex_t*;
58
59 constexpr priority_mutex() noexcept = default;
60 priority_mutex(const priority_mutex&) = delete;
61 priority_mutex& operator=(const priority_mutex&) = delete;
62
63 // Lock the mutex, blocking until it's available.
64 void lock() { pthread_mutex_lock(&m_mutex); }
65
66 // Unlock the mutex.
67 void unlock() { pthread_mutex_unlock(&m_mutex); }
68
69 // Tries to lock the mutex.
70 bool try_lock() noexcept { return !pthread_mutex_trylock(&m_mutex); }
71
72 pthread_mutex_t* native_handle() { return &m_mutex; }
73
74 private:
75// Do the equivalent of setting PTHREAD_PRIO_INHERIT.
76#ifdef __PTHREAD_MUTEX_HAVE_PREV
77 pthread_mutex_t m_mutex = {{0, 0, 0, 0, 0x20, __PTHREAD_SPINS, {0, 0}}};
78#else
79 pthread_mutex_t m_mutex = {{0, 0, 0, 0x20, 0, {__PTHREAD_SPINS}}};
80#endif
81};
82
83#endif // defined(WPI_USE_PRIORITY_MUTEX) && defined(__linux__)
84
85} // namespace wpi
Definition: ntcore_cpp.h:26