Skip to content

Commit

Permalink
Update runnable to use atomic. (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
hokyungh authored Sep 13, 2022
1 parent d156faf commit 267012e
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions chime-sdk-signaling-cpp/src/utils/runnable.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#ifndef SIGNALING_SDK_RUNNABLE_H
#define SIGNALING_SDK_RUNNABLE_H

#include <atomic>
#include <thread>

namespace chime {
Expand All @@ -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
Expand All @@ -38,9 +47,9 @@ class Runnable {

private:
std::thread run_thread_;
bool running_ = false;
std::atomic<bool> running_ = false;
};

} // namespace chime

#endif // SIGNALING_SDK_RUNNABLE_H
#endif // SIGNALING_SDK_RUNNABLE_H

0 comments on commit 267012e

Please sign in to comment.