From cf2d6b85ea1e5bdd31c44aeb9e471222d96f5458 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 8 Sep 2022 11:26:19 -0400 Subject: [PATCH] Fix unlocking in FreeRTOS _RunEventLoop. Ensure we always start with an empty event queue after FreeRTOS _InitChipStack. --- .../GenericPlatformManagerImpl_FreeRTOS.ipp | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp b/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp index 24fb409e627bb1..710d1c63fe3e24 100644 --- a/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp +++ b/src/include/platform/internal/GenericPlatformManagerImpl_FreeRTOS.ipp @@ -85,6 +85,12 @@ CHIP_ERROR GenericPlatformManagerImpl_FreeRTOS::_InitChipStack(void) ExitNow(err = CHIP_ERROR_NO_MEMORY); } } + else + { + // Clear out any events that might be stuck in the queue, so we start + // with a clean slate, as if we had just re-created the queue. + xQueueReset(mChipEventQueue); + } mShouldRunEventLoop.store(false); @@ -158,7 +164,7 @@ void GenericPlatformManagerImpl_FreeRTOS::_RunEventLoop(void) ChipDeviceEvent event; // Lock the CHIP stack. - Impl()->LockChipStack(); + StackLock lock; bool oldShouldRunEventLoop = false; if (!mShouldRunEventLoop.compare_exchange_strong(oldShouldRunEventLoop /* expected */, true /* desired */)) @@ -211,13 +217,13 @@ void GenericPlatformManagerImpl_FreeRTOS::_RunEventLoop(void) waitTime = portMAX_DELAY; } - // Unlock the CHIP stack, allowing other threads to enter CHIP while the event loop thread is sleeping. - Impl()->UnlockChipStack(); - - BaseType_t eventReceived = xQueueReceive(mChipEventQueue, &event, waitTime); - - // Lock the CHIP stack. - Impl()->LockChipStack(); + BaseType_t eventReceived = pdFALSE; + { + // Unlock the CHIP stack, allowing other threads to enter CHIP while + // the event loop thread is sleeping. + StackUnlock unlock; + eventReceived = xQueueReceive(mChipEventQueue, &event, waitTime); + } // If an event was received, dispatch it. Continue receiving events from the queue and // dispatching them until the queue is empty.