WPILibC++ 2027.0.0-alpha-2
Loading...
Searching...
No Matches
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_SYSTEMCORE__) && !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 // from glibc sysdeps/nptl/pthreadP.h: PTHREAD_MUTEX_PRIO_INHERIT_NP = 32
47 pthread_mutex_t m_mutex = {
48 {__PTHREAD_MUTEX_INITIALIZER(0x20 | PTHREAD_MUTEX_RECURSIVE_NP)}};
49};
50
51class priority_mutex {
52 public:
53 using native_handle_type = pthread_mutex_t*;
54
55 constexpr priority_mutex() noexcept = default;
56 priority_mutex(const priority_mutex&) = delete;
57 priority_mutex& operator=(const priority_mutex&) = delete;
58
59 // Lock the mutex, blocking until it's available.
60 void lock() { pthread_mutex_lock(&m_mutex); }
61
62 // Unlock the mutex.
63 void unlock() { pthread_mutex_unlock(&m_mutex); }
64
65 // Tries to lock the mutex.
66 bool try_lock() noexcept { return !pthread_mutex_trylock(&m_mutex); }
67
68 pthread_mutex_t* native_handle() { return &m_mutex; }
69
70 private:
71 // Do the equivalent of setting PTHREAD_PRIO_INHERIT.
72 // from glibc sysdeps/nptl/pthreadP.h: PTHREAD_MUTEX_PRIO_INHERIT_NP = 32
73 pthread_mutex_t m_mutex = {{__PTHREAD_MUTEX_INITIALIZER(0x20)}};
74};
75
76#endif // defined(WPI_USE_PRIORITY_MUTEX) && defined(__linux__)
77
78} // namespace wpi
Definition ntcore_cpp.h:26