TinyRobotics
Loading...
Searching...
No Matches
Mutex.h
1#pragma once
2
3#include "TinyRobotics/utils/Config.h"
4
5#ifdef USE_STD_CONCURRENCY
6#include <atomic>
7#include <mutex>
8#endif
9
10namespace tinyrobotics {
11
12/**
13 * @class MutexBase
14 * @ingroup concurrency
15 * @brief Empty Mutex implementation which does nothing
16 * @author Phil Schatzmann
17 */
18class MutexBase {
19 public:
20 virtual void lock() {}
21 virtual void unlock() {}
22};
23
24#if defined(USE_STD_CONCURRENCY)
25
26class SpinLock : public MutexBase {
27 void lock() {
28 for (;;) {
29 // Optimistically assume the lock is free on the first try
30 if (!lock_.exchange(true, std::memory_order_acquire)) {
31 return;
32 }
33 // Wait for lock to be released without generating cache misses
34 while (lock_.load(std::memory_order_relaxed)) {
35 // Issue X86 PAUSE or ARM YIELD instruction to reduce contention between
36 // hyper-threads
37 //__builtin_ia32_pause();
38 delay(1);
39 }
40 }
41 }
42
43 bool try_lock() {
44 // First do a relaxed load to check if lock is free in order to prevent
45 // unnecessary cache misses if someone does while(!try_lock())
46 return !lock_.load(std::memory_order_relaxed) &&
47 !lock_.exchange(true, std::memory_order_acquire);
48 }
49
50 void unlock() { lock_.store(false, std::memory_order_release); }
51
52 protected:
53 volatile std::atomic<bool> lock_ = {0};
54};
55
56
57/**
58 * @brief Mutex implemntation based on std::mutex
59 * @ingroup concurrency
60 * @author Phil Schatzmann
61
62 */
63class StdMutex : public MutexBase {
64 public:
65 void lock() override { std_mutex.lock(); }
66 void unlock() override { std_mutex.unlock(); }
67
68 protected:
69 std::mutex std_mutex;
70};
71
72/**
73 * @brief Mutex implemntation based on std::mutex
74 * @ingroup concurrency
75 * @author Phil Schatzmann
76
77 */
78class StdRecursiveMutex : public MutexBase {
79 public:
80 void lock() override { std_mutex.lock(); }
81 void unlock() override { std_mutex.unlock(); }
82
83 protected:
84 std::recursive_mutex std_mutex;
85};
86
87
88#endif
89
90} // namespace tinyrobotics
Empty Mutex implementation which does nothing.
Definition: Mutex.h:18