From 0b26e0c7c9caf87f0d4e98d5a6e4614d584c688a Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Mon, 19 Jan 2026 20:38:51 +0800 Subject: [PATCH] feat: semaphore guard helper --- main/common/semaphore_guard.h | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 main/common/semaphore_guard.h diff --git a/main/common/semaphore_guard.h b/main/common/semaphore_guard.h new file mode 100644 index 0000000..f285c60 --- /dev/null +++ b/main/common/semaphore_guard.h @@ -0,0 +1,28 @@ +#pragma once +#include "freertos/semphr.h" +#include "freertos/portmacro.h" + +struct SemaphoreGuard { +public: + const SemaphoreHandle_t semaphore; + + SemaphoreGuard(SemaphoreHandle_t semaphore) : semaphore(semaphore) { } + + portBASE_TYPE take(TickType_t ticks_to_wait = portMAX_DELAY) { + portBASE_TYPE result = xSemaphoreTake(this->semaphore, ticks_to_wait); + taken = (result == pdTRUE); + return result; + } + + ~SemaphoreGuard() { + if (taken) { + xSemaphoreGive(this->semaphore); + } + } + +private: + // prevent copying + SemaphoreGuard(const SemaphoreGuard&) = delete; + SemaphoreGuard& operator=(const SemaphoreGuard&) = delete; + bool taken = false; +};