arduino-audio-tools
LockGuard.h
1 #pragma once
2 #include "AudioConfig.h"
3 #include "AudioTools/CoreAudio/AudioLogger.h"
4 
5 #ifdef USE_STD_CONCURRENCY
6 # include <mutex>
7 #endif
8 
9 #ifdef ESP32
10 # include "freertos/FreeRTOS.h"
11 # include "freertos/semphr.h"
12 #else
13 # include "FreeRTOS.h"
14 # include "semphr.h"
15 #endif
16 
17 namespace audio_tools {
18 
25 class MutexBase {
26 public:
27  virtual void lock() {}
28  virtual void unlock() {}
29 };
30 
31 #if defined(USE_STD_CONCURRENCY)
32 
39 class StdMutex : public MutexBase {
40 public:
41  void lock() override { std_mutex.lock(); }
42  void unlock() override { std_mutex.unlock(); }
43 
44 protected:
45  std::mutex std_mutex;
46 };
47 
48 #endif
49 
50 
57 class Mutex : public MutexBase {
58 public:
59  Mutex() {
60  TRACED();
61  xSemaphore = xSemaphoreCreateBinary();
62  xSemaphoreGive(xSemaphore);
63  }
64  ~Mutex() {
65  TRACED();
66  vSemaphoreDelete(xSemaphore);
67  }
68  void lock() override {
69  TRACED();
70  xSemaphoreTake(xSemaphore, portMAX_DELAY);
71  }
72  void unlock() override {
73  TRACED();
74  xSemaphoreGive(xSemaphore);
75  }
76 
77 protected:
78  SemaphoreHandle_t xSemaphore = NULL;
79 };
80 
81 
91 class LockGuard {
92 public:
93  LockGuard(Mutex &mutex) {
94  TRACED();
95  p_mutex = &mutex;
96  p_mutex->lock();
97  }
98  LockGuard(Mutex *mutex) {
99  TRACED();
100  p_mutex = mutex;
101  p_mutex->lock();
102  }
103  ~LockGuard() {
104  TRACED();
105  p_mutex->unlock();
106  }
107 
108 protected:
109  Mutex *p_mutex = nullptr;
110 };
111 
112 }
113 
RAII implementaion using a Mutex: Only a few microcontrollers provide lock guards,...
Definition: LockGuard.h:91
Empty Mutex implementation which does nothing.
Definition: LockGuard.h:25
Mutex implemntation using FreeRTOS.
Definition: LockGuard.h:57
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AudioConfig.h:868