Last active
May 24, 2025 18:04
-
-
Save CelliesProjects/5adbf69c279c998c13027071f56dfbbd to your computer and use it in GitHub Desktop.
A scoped mutex for a FreeRTOS semaphore handle that prevents deadlocks by ensuring that the mutex is always released, even if exceptions are thrown or the code exits early
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef SCOPEDMUTEX_HPP_ | |
#define SCOPEDMUTEX_HPP_ | |
#include <Arduino.h> | |
#include <freertos/semphr.h> | |
class ScopedMutex | |
{ | |
private: | |
SemaphoreHandle_t &mutex; | |
bool locked; | |
public: | |
explicit ScopedMutex(SemaphoreHandle_t &m, TickType_t timeout = portMAX_DELAY) | |
: mutex(m), locked(xSemaphoreTake(mutex, timeout)) {} | |
ScopedMutex(const ScopedMutex &) = delete; | |
ScopedMutex &operator=(const ScopedMutex &) = delete; | |
~ScopedMutex() | |
{ | |
if (locked) | |
xSemaphoreGive(mutex); | |
} | |
bool acquired() const { return locked; } | |
}; | |
#endif // SCOPEDMUTEX_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment