Skip to content

Instantly share code, notes, and snippets.

@CelliesProjects
Last active May 24, 2025 18:04
Show Gist options
  • Save CelliesProjects/5adbf69c279c998c13027071f56dfbbd to your computer and use it in GitHub Desktop.
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
#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