Class:
/** * @brief The FreeRtosScopedLock class, provides an RAII * style approach to locking a FreeRTOS mutex, * similar to C++11 std::scoped_lock<> */ class FreeRtosScopedLock { public: explicit FreeRtosScopedLock(SemaphoreHandle_t mutex) : mMutex(mutex) { xSemaphoreTakeRecursive(mMutex, portMAX_DELAY); //for demo, assume success } ~FreeRtosScopedLock() { xSemaphoreGiveRecursive(mMutex); //for demo, assume success } private: SemaphoreHandle_t mMutex; };
Usage example:
bool AccessMyDeviceNewStyle() { ScopedLock lockItDown(mDevMutex); if (!SomeGuardCheck()) { return false; } if (!AnotherGuardCheck()) { return false; } //Do Stuff return true; }
References:
https://covemountainsoftware.com/2019/11/26/why-i-prefer-c-raii-all-the-things/
https://blogs.sw.siemens.com/embedded-software/2017/03/27/more-on-c-with-an-rtos/
https://embeddedartistry.com/blog/2018/02/08/implementing-stdmutex-with-freertos/