Skip to content

Instantly share code, notes, and snippets.

@mtao
Created December 5, 2017 04:09
Show Gist options
  • Save mtao/563298eb33f79fdcff60fb89489108a9 to your computer and use it in GitHub Desktop.
Save mtao/563298eb33f79fdcff60fb89489108a9 to your computer and use it in GitHub Desktop.
simple example for using cpp thread / mutex / condition_variable to toggle running a daemon in the background
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
#include <mutex>
#include <atomic>
std::condition_variable activity_cv;
std::mutex activity_mutex;
std::atomic<bool> run_daemon = false;
void process() {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << "Process!" << std::endl;
}
void daemon() {
while(true) {
std::unique_lock<std::mutex> lk(activity_mutex);
std::cerr << "Waiting for permission to run_daemon \n";
activity_cv.wait(lk, []{return bool(run_daemon);});
while(run_daemon) {
process();
}
}
}
int main() {
std::thread daemon_thread(daemon);
while(true) {
if(run_daemon) {
std::this_thread::sleep_for(std::chrono::seconds(1));
} else {
std::this_thread::sleep_for(std::chrono::seconds(2));
}
run_daemon = !run_daemon;//toggle running daemon
activity_cv.notify_all();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment