arduino-audio-tools
Loading...
Searching...
No Matches
Mutex.h
Go to the documentation of this file.
1#pragma once
2
3#include "AudioToolsConfig.h"
4
5#include <atomic>
6
7namespace audio_tools {
8
15class MutexBase {
16 public:
17 virtual void lock() {}
18 virtual void unlock() {}
19};
20
28class SpinLock : public MutexBase {
29 public:
30 void lock() override {
31 for (;;) {
32 // Optimistically assume the lock is free on the first try
33 if (!lock_.exchange(true, std::memory_order_acquire)) {
34 return;
35 }
36 // Wait for lock to be released without generating cache misses
37 while (lock_.load(std::memory_order_relaxed)) {
38 // Issue X86 PAUSE or ARM YIELD instruction to reduce contention between
39 // hyper-threads
40 //__builtin_ia32_pause();
41 delay(1);
42 }
43 }
44 }
45
46 bool try_lock() {
47 // First do a relaxed load to check if lock is free in order to prevent
48 // unnecessary cache misses if someone does while(!try_lock())
49 return !lock_.load(std::memory_order_relaxed) &&
50 !lock_.exchange(true, std::memory_order_acquire);
51 }
52
53 void unlock() override { lock_.store(false, std::memory_order_release); }
54
55 protected:
56 std::atomic<bool> lock_ = {false};
57};
58
59} // namespace audio_tools
Empty Mutex implementation which does nothing.
Definition Mutex.h:15
virtual void lock()
Definition Mutex.h:17
virtual void unlock()
Definition Mutex.h:18
Busy-wait lock based on std::atomic - available on all platforms that support <atomic>.
Definition Mutex.h:28
void unlock() override
Definition Mutex.h:53
std::atomic< bool > lock_
Definition Mutex.h:56
bool try_lock()
Definition Mutex.h:46
void lock() override
Definition Mutex.h:30
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition LMSEchoCancellationStream.h:6
void delay(uint32_t ms)
Definition Arduino.h:259