FastLED 3.9.15
Loading...
Searching...
No Matches
mutex.h
Go to the documentation of this file.
1#pragma once
2
3#include "fl/thread.h"
4#include "fl/assert.h"
5
6#if FASTLED_MULTITHREADED
7#include <mutex> // ok include
8#endif
9
10namespace fl {
11
12template <typename T> class MutexFake;
13class MutexReal;
14
15#if FASTLED_MULTITHREADED
16using mutex = MutexReal;
17#else
19#endif
20
22
23template <typename T> class MutexFake {
24 private:
25 int mLockCount = 0;
26
27 public:
28 MutexFake() = default;
29
30 // Non-copyable and non-movable
31 MutexFake(const MutexFake&) = delete;
32 MutexFake& operator=(const MutexFake&) = delete;
33 MutexFake(MutexFake&&) = delete;
35
36 // Recursive fake mutex operations
37 void lock() {
38 // In single-threaded mode, we just track the lock count for debugging
39 mLockCount++;
40 }
41
42 void unlock() {
43 // In single-threaded mode, we just track the lock count for debugging
44 FL_ASSERT(mLockCount > 0, "MutexFake: unlock called without matching lock");
45 mLockCount--;
46 }
47
48 bool try_lock() {
49 // In single-threaded mode, always succeed and increment count
50 mLockCount++;
51 return true;
52 }
53};
54
55
56#if FASTLED_MULTITHREADED
57class MutexReal : public std::recursive_mutex {
58 public:
59 MutexReal() = default;
60
61 // Non-copyable and non-movable (inherited from std::recursive_mutex)
62 MutexReal(const MutexReal&) = delete;
63 MutexReal& operator=(const MutexReal&) = delete;
64 MutexReal(MutexReal&&) = delete;
65 MutexReal& operator=(MutexReal&&) = delete;
66
67 // Mutex operations are inherited from std::recursive_mutex:
68 // - void lock() - can be called multiple times by the same thread
69 // - void unlock() - must be called the same number of times as lock()
70 // - bool try_lock() - can succeed multiple times for the same thread
71};
72#endif
73
74template<typename MutexType>
76 public:
77 lock_guard(MutexType& mutex) : mMutex(mutex) {
78 mMutex.lock();
79 }
80
82 mMutex.unlock();
83 }
84
85 // Non-copyable and non-movable
86 lock_guard(const lock_guard&) = delete;
87 lock_guard& operator=(const lock_guard&) = delete;
90
91 private:
92 MutexType& mMutex;
93};
94
95} // namespace fl
#define FL_ASSERT(x, MSG)
Definition assert.h:6
void lock()
Definition mutex.h:37
MutexFake & operator=(const MutexFake &)=delete
void unlock()
Definition mutex.h:42
MutexFake(const MutexFake &)=delete
bool try_lock()
Definition mutex.h:48
MutexFake()=default
MutexFake(MutexFake &&)=delete
MutexFake & operator=(MutexFake &&)=delete
lock_guard(MutexType &mutex)
Definition mutex.h:77
lock_guard(lock_guard &&)=delete
lock_guard & operator=(const lock_guard &)=delete
lock_guard & operator=(lock_guard &&)=delete
MutexType & mMutex
Definition mutex.h:92
lock_guard(const lock_guard &)=delete
MutexFake< void > mutex
Definition mutex.h:18
IMPORTANT!
Definition crgb.h:20