From a0cbb80f581d691c02bd932169f39c7a876c11ee Mon Sep 17 00:00:00 2001 From: Hao Chen Date: Mon, 8 Mar 2021 12:04:00 -0800 Subject: [PATCH] Gracefully stop the GeneratorHub worker thread in destructor To unit test the virtualized VHAL, GeneratorHub needs to be destructable Test: run unit tests in pa/1878260 Bug: 181371253 Change-Id: Icfd3007a194da7ade037e359858b3dd48f24a0d6 --- .../2.0/default/impl/vhal_v2_0/GeneratorHub.cpp | 17 ++++++++++++++--- .../2.0/default/impl/vhal_v2_0/GeneratorHub.h | 3 ++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.cpp b/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.cpp index 548285abfb..9be9ea7c8e 100644 --- a/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.cpp +++ b/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.cpp @@ -31,6 +31,14 @@ namespace impl { GeneratorHub::GeneratorHub(const OnHalEvent& onHalEvent) : mOnHalEvent(onHalEvent), mThread(&GeneratorHub::run, this) {} +GeneratorHub::~GeneratorHub() { + mShuttingDownFlag.store(true); + mCond.notify_all(); + if (mThread.joinable()) { + mThread.join(); + } +} + void GeneratorHub::registerGenerator(int32_t cookie, FakeValueGeneratorPtr generator) { { std::lock_guard g(mLock); @@ -58,15 +66,18 @@ void GeneratorHub::unregisterGenerator(int32_t cookie) { } void GeneratorHub::run() { - while (true) { + while (!mShuttingDownFlag.load()) { std::unique_lock g(mLock); // Pop events whose generator does not exist (may be already unregistered) while (!mEventQueue.empty() && mGenerators.find(mEventQueue.top().cookie) == mGenerators.end()) { mEventQueue.pop(); } - // Wait until event queue is not empty - mCond.wait(g, [this] { return !mEventQueue.empty(); }); + // Wait until event queue is not empty or shutting down flag is set + mCond.wait(g, [this] { return !mEventQueue.empty() || mShuttingDownFlag.load(); }); + if (mShuttingDownFlag.load()) { + break; + } const VhalEvent& curEvent = mEventQueue.top(); diff --git a/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.h b/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.h index dcf6a4f06e..b25dbf1c09 100644 --- a/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.h +++ b/automotive/vehicle/2.0/default/impl/vhal_v2_0/GeneratorHub.h @@ -58,7 +58,7 @@ private: public: GeneratorHub(const OnHalEvent& onHalEvent); - ~GeneratorHub() = default; + ~GeneratorHub(); /** * Register a new generator. The generator will be discarded if it could not produce next event. @@ -84,6 +84,7 @@ private: mutable std::mutex mLock; std::condition_variable mCond; std::thread mThread; + std::atomic mShuttingDownFlag{false}; }; } // namespace impl