Last active
February 9, 2022 06:33
-
-
Save marceljanerfont/90d5f4b9cae2e3cd525a74bdc9d29dee to your computer and use it in GitHub Desktop.
C++ simple thread worker class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <condition_variable> | |
class Worker { | |
public: | |
Worker() { | |
start(); | |
} | |
~Worker() { | |
stop(); | |
} | |
private: | |
void start() { | |
terminated_ = false; | |
thread_ = std::thread(&Worker::execute, this); | |
} | |
void stop() { | |
terminated_ = true; | |
thread_wait_.notify_one(); | |
thread_.join(); | |
} | |
void execute() { | |
while (!terminated_) { | |
// sleep 2 seconds | |
std::unique_lock<std::mutex> locker(mutex_); | |
thread_wait_.wait_for(locker, std::chrono::seconds(2)); | |
} | |
} | |
std::thread thread_; | |
std::mutex mutex_; | |
std::atomic_bool terminated_ {false}; | |
std::condition_variable thread_wait_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment