Skip to content

Instantly share code, notes, and snippets.

@marceljanerfont
Last active February 9, 2022 06:33
Show Gist options
  • Save marceljanerfont/90d5f4b9cae2e3cd525a74bdc9d29dee to your computer and use it in GitHub Desktop.
Save marceljanerfont/90d5f4b9cae2e3cd525a74bdc9d29dee to your computer and use it in GitHub Desktop.
C++ simple thread worker class
#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