From 267012e5b0fe80adb231712a657b25f5faae1f52 Mon Sep 17 00:00:00 2001 From: Nick Hwang <57926812+hokyungh@users.noreply.github.com> Date: Tue, 13 Sep 2022 12:15:39 -0700 Subject: [PATCH] Update runnable to use atomic. (#8) --- chime-sdk-signaling-cpp/src/utils/runnable.h | 33 +++++++++++++------- 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/chime-sdk-signaling-cpp/src/utils/runnable.h b/chime-sdk-signaling-cpp/src/utils/runnable.h index 4ece899..f7eefce 100644 --- a/chime-sdk-signaling-cpp/src/utils/runnable.h +++ b/chime-sdk-signaling-cpp/src/utils/runnable.h @@ -3,6 +3,7 @@ #ifndef SIGNALING_SDK_RUNNABLE_H #define SIGNALING_SDK_RUNNABLE_H +#include #include namespace chime { @@ -11,22 +12,30 @@ namespace chime { // and Poll() should be overridden with polling logic. class Runnable { public: + ~Runnable() { + bool expected = true; + if (running_.compare_exchange_strong(expected, false)) { + StopRun(); + } + } // Implementation may require this to be called. // It is expected that this call is non-blocking. virtual void Run() { - if (running_) return; - running_ = true; - run_thread_ = std::thread([=]() { - while (running_) { - Poll(); - } - }); + bool expected = false; + if (running_.compare_exchange_strong(expected, true)) { + run_thread_ = std::thread([=]() { + while (running_) { + Poll(); + } + }); + } } virtual void StopRun() { - if (!running_) return; - running_ = false; - if (run_thread_.joinable()) run_thread_.join(); + bool expected = true; + if (running_.compare_exchange_strong(expected, false)) { + if (run_thread_.joinable()) run_thread_.join(); + } } // Implementation may require this to be called in order @@ -38,9 +47,9 @@ class Runnable { private: std::thread run_thread_; - bool running_ = false; + std::atomic running_ = false; }; } // namespace chime -#endif // SIGNALING_SDK_RUNNABLE_H +#endif // SIGNALING_SDK_RUNNABLE_H \ No newline at end of file