Skip to content

Commit

Permalink
Wait for lambdas before stopping loop task
Browse files Browse the repository at this point in the history
  • Loading branch information
arkq committed Apr 24, 2023
1 parent 93e0791 commit 8746d0c
Showing 1 changed file with 46 additions and 2 deletions.
48 changes: 46 additions & 2 deletions src/platform/tests/TestPlatformMgr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
*/

#include <atomic>
#include <condition_variable>
#include <inttypes.h>
#include <mutex>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
Expand All @@ -42,6 +44,38 @@ using namespace chip::Logging;
using namespace chip::Inet;
using namespace chip::DeviceLayer;

namespace {

/**
* @brief Simple barrier implementation.
* We can use C++20 std::barrier once we support it.
*/
class Barrier
{
public:
explicit Barrier(size_t count) : mCount(count) {}

void arrive()
{
std::unique_lock<std::mutex> lock(mMutex);
mCount--;
mCond.notify_all();
}

void wait()
{
std::unique_lock<std::mutex> lock(mMutex);
mCond.wait(lock, [this] { return mCount == 0; });
}

private:
std::mutex mMutex;
std::condition_variable mCond;
size_t mCount;
};

} // namespace

// =================================
// Unit tests
// =================================
Expand All @@ -67,12 +101,22 @@ static void TestPlatformMgr_BasicEventLoopTask(nlTestSuite * inSuite, void * inC
err = PlatformMgr().StartEventLoopTask();
NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);

Barrier sync(2);

// Verify that the event loop will not exit until we tell it to by
// scheduling few lambdas (for the test to pass, the event loop will
// have to process more than one event).
DeviceLayer::SystemLayer().ScheduleLambda([&counterRun]() { counterRun++; });
DeviceLayer::SystemLayer().ScheduleLambda([&]() {
counterRun++;
sync.arrive();
});
chip::test_utils::SleepMillis(10);
DeviceLayer::SystemLayer().ScheduleLambda([&counterRun]() { counterRun++; });
DeviceLayer::SystemLayer().ScheduleLambda([&]() {
counterRun++;
sync.arrive();
});

sync.wait();

err = PlatformMgr().StopEventLoopTask();
NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR);
Expand Down

0 comments on commit 8746d0c

Please sign in to comment.