Files
allwpilib/hal/include/HAL/cpp/priority_mutex.h
Tyler Veness c0ecde302f Replaced instances of std::unique_lock with std::lock_guard where possible
If a lock is used with a mutex that doesn't need to be unlocked again before the lock is destroyed, std::lock_guard can be more efficient than std::unique_lock due to less overhead.

This commit also removes a redundant set of curly braces in PIDController.cpp intended to constrain a lock's scope.

Change-Id: Idd692ce439528ddb319a4c62c40c7351a664eb97
2015-10-04 13:20:11 -07:00

77 lines
1.9 KiB
C++

#pragma once
// Allows usage with std::lock_guard without including <mutex> separately
#include <mutex>
#ifdef FRC_SIMULATOR
// We do not want to use pthreads if in the simulator; however, in the
// simulator, we do not care about priority inversion.
typedef std::mutex priority_mutex;
typedef std::recursive_mutex priority_recursive_mutex;
#else // Covers rest of file.
#include <pthread.h>
class priority_recursive_mutex {
public:
typedef pthread_mutex_t *native_handle_type;
constexpr priority_recursive_mutex() noexcept = default;
priority_recursive_mutex(const priority_recursive_mutex &) = delete;
priority_recursive_mutex &operator=(const priority_recursive_mutex &) = delete;
// Lock the mutex, blocking until it's available.
void lock();
// Unlock the mutex.
void unlock();
// Tries to lock the mutex.
bool try_lock() noexcept;
pthread_mutex_t *native_handle();
private:
// Do the equivalent of setting PTHREAD_PRIO_INHERIT and
// PTHREAD_MUTEX_RECURSIVE_NP.
#if __WORDSIZE == 64
pthread_mutex_t m_mutex = {
{0, 0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, 0, {0, 0}}};
#else
pthread_mutex_t m_mutex = {
{0, 0, 0, 0x20 | PTHREAD_MUTEX_RECURSIVE_NP, 0, {0}}};
#endif
};
class priority_mutex {
public:
typedef pthread_mutex_t *native_handle_type;
constexpr priority_mutex() noexcept = default;
priority_mutex(const priority_mutex &) = delete;
priority_mutex &operator=(const priority_mutex &) = delete;
// Lock the mutex, blocking until it's available.
void lock();
// Unlock the mutex.
void unlock();
// Tries to lock the mutex.
bool try_lock() noexcept;
pthread_mutex_t *native_handle();
private:
// Do the equivalent of setting PTHREAD_PRIO_INHERIT.
#if __WORDSIZE == 64
pthread_mutex_t m_mutex = {
{0, 0, 0, 0, 0x20, 0, 0, {0, 0}}};
#else
pthread_mutex_t m_mutex = {
{0, 0, 0, 0x20, 0, {0}}};
#endif
};
#endif // FRC_SIMULATOR