arduino-audio-tools
All Classes Namespaces Files Functions Variables Typedefs Enumerations Friends Modules Pages
Mutex.h
1#pragma once
2
3#include "AudioToolsConfig.h"
4
5#ifdef USE_STD_CONCURRENCY
6#include <atomic>
7#include <mutex>
8#endif
9
10namespace audio_tools {
11
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
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#endif
73
74} // namespace audio_tools
Empty Mutex implementation which does nothing.
Definition Mutex.h:18
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition AudioCodecsBase.h:10