arduino-audio-tools
Mutex.h
1 #pragma once
2 #include <atomic>
3 
4 #include "AudioConfig.h"
5 
6 #ifdef USE_STD_CONCURRENCY
7 #include <mutex>
8 #endif
9 
10 namespace audio_tools {
11 
18 class MutexBase {
19  public:
20  virtual void lock() {}
21  virtual void unlock() {}
22 };
23 
24 class SpinLock : public MutexBase {
25  void lock() {
26  for (;;) {
27  // Optimistically assume the lock is free on the first try
28  if (!lock_.exchange(true, std::memory_order_acquire)) {
29  return;
30  }
31  // Wait for lock to be released without generating cache misses
32  while (lock_.load(std::memory_order_relaxed)) {
33  // Issue X86 PAUSE or ARM YIELD instruction to reduce contention between
34  // hyper-threads
35  //__builtin_ia32_pause();
36  delay(1);
37  }
38  }
39  }
40 
41  bool try_lock() {
42  // First do a relaxed load to check if lock is free in order to prevent
43  // unnecessary cache misses if someone does while(!try_lock())
44  return !lock_.load(std::memory_order_relaxed) &&
45  !lock_.exchange(true, std::memory_order_acquire);
46  }
47 
48  void unlock() { lock_.store(false, std::memory_order_release); }
49 
50  protected:
51  volatile std::atomic<bool> lock_ = {0};
52 };
53 
54 #if defined(USE_STD_CONCURRENCY)
55 
62 class StdMutex : public MutexBase {
63  public:
64  void lock() override { std_mutex.lock(); }
65  void unlock() override { std_mutex.unlock(); }
66 
67  protected:
68  std::mutex std_mutex;
69 };
70 
71 #endif
72 
73 } // namespace audio_tools
Empty Mutex implementation which does nothing.
Definition: Mutex.h:18
Definition: Mutex.h:24
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AudioConfig.h:872