From d36fe9be6b522a3dade389213a0bb7e26a169627 Mon Sep 17 00:00:00 2001 From: jacqueline Date: Tue, 7 Nov 2023 08:30:26 +1100 Subject: [PATCH] Use atomics for new file notification instead of a semaphore --- src/audio/fatfs_audio_input.cpp | 28 +++++++++++++------------ src/audio/include/fatfs_audio_input.hpp | 2 +- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/audio/fatfs_audio_input.cpp b/src/audio/fatfs_audio_input.cpp index 4c5e981b..b919a3a8 100644 --- a/src/audio/fatfs_audio_input.cpp +++ b/src/audio/fatfs_audio_input.cpp @@ -47,12 +47,10 @@ FatfsAudioInput::FatfsAudioInput(database::ITagParser& tag_parser) tag_parser_(tag_parser), new_stream_mutex_(), new_stream_(), - has_new_stream_(xSemaphoreCreateBinary()), + has_new_stream_(false), pending_path_() {} -FatfsAudioInput::~FatfsAudioInput() { - vSemaphoreDelete(has_new_stream_); -} +FatfsAudioInput::~FatfsAudioInput() {} auto FatfsAudioInput::SetPath(std::future> fut) -> void { @@ -61,36 +59,40 @@ auto FatfsAudioInput::SetPath(std::future> fut) new database::FutureFetcher>( std::move(fut))); - xSemaphoreGive(has_new_stream_); + has_new_stream_ = true; + has_new_stream_.notify_one(); } auto FatfsAudioInput::SetPath(const std::pmr::string& path) -> void { std::lock_guard guard{new_stream_mutex_}; if (OpenFile(path)) { - xSemaphoreGive(has_new_stream_); + has_new_stream_ = true; + has_new_stream_.notify_one(); } } auto FatfsAudioInput::SetPath() -> void { std::lock_guard guard{new_stream_mutex_}; new_stream_.reset(); - xSemaphoreGive(has_new_stream_); + has_new_stream_ = true; + has_new_stream_.notify_one(); } auto FatfsAudioInput::HasNewStream() -> bool { - bool res = xSemaphoreTake(has_new_stream_, 0); - if (res) { - xSemaphoreGive(has_new_stream_); - } - return res; + return has_new_stream_; } auto FatfsAudioInput::NextStream() -> std::shared_ptr { while (true) { - xSemaphoreTake(has_new_stream_, portMAX_DELAY); + has_new_stream_.wait(false); { std::lock_guard guard{new_stream_mutex_}; + if (!has_new_stream_.exchange(false)) { + // If the new stream went away, then we need to go back to waiting. + continue; + } + // If the path is a future, then wait for it to complete. if (pending_path_) { auto res = pending_path_->Result(); diff --git a/src/audio/include/fatfs_audio_input.hpp b/src/audio/include/fatfs_audio_input.hpp index b7b1d18e..08527350 100644 --- a/src/audio/include/fatfs_audio_input.hpp +++ b/src/audio/include/fatfs_audio_input.hpp @@ -58,7 +58,7 @@ class FatfsAudioInput : public IAudioSource { std::mutex new_stream_mutex_; std::shared_ptr new_stream_; - SemaphoreHandle_t has_new_stream_; + std::atomic has_new_stream_; std::unique_ptr>> pending_path_;