worker: put this threaded worker into a class for cleanliness
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
parent
f332b0868a
commit
06b00b9f97
1 changed files with 37 additions and 18 deletions
43
worker.cpp
43
worker.cpp
|
@ -7,26 +7,45 @@
|
||||||
// https://en.cppreference.com/w/cpp/thread/mutex
|
// https://en.cppreference.com/w/cpp/thread/mutex
|
||||||
// https://en.cppreference.com/w/cpp/thread/condition_variable
|
// https://en.cppreference.com/w/cpp/thread/condition_variable
|
||||||
|
|
||||||
std::mutex mtx;
|
namespace Dang {
|
||||||
std::condition_variable cv;
|
class Worker {
|
||||||
bool ready = false;
|
public:
|
||||||
|
Worker() {
|
||||||
|
this->ready = false;
|
||||||
|
//init();
|
||||||
|
};
|
||||||
|
|
||||||
void worker() {
|
void run() {
|
||||||
std::unique_lock<std::mutex> lock(mtx);
|
std::unique_lock<std::mutex> lock(this->mtx);
|
||||||
cv.wait(lock, [] { return ready; }); // Wait until 'ready' is set to true
|
this->cv.wait(lock, [this] { return this->ready; }); // Wait until 'ready' is set to true
|
||||||
std::cout << "Daemon process woke up!" << std::endl;
|
std::cout << "Daemon process woke up!" << std::endl;
|
||||||
}
|
};
|
||||||
|
|
||||||
int main() {
|
int work() {
|
||||||
std::thread daemon(worker);
|
std::thread daemon([this] {this->run();});
|
||||||
|
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(5));
|
std::this_thread::sleep_for(std::chrono::seconds(5));
|
||||||
{
|
{
|
||||||
std::lock_guard<std::mutex> lock(mtx);
|
std::lock_guard<std::mutex> lock(this->mtx);
|
||||||
ready = true;
|
this->ready = true;
|
||||||
}
|
}
|
||||||
cv.notify_one();
|
this->cv.notify_one();
|
||||||
|
|
||||||
daemon.join();
|
daemon.join();
|
||||||
return 0;
|
return 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::mutex mtx;
|
||||||
|
std::condition_variable cv;
|
||||||
|
bool ready;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
Dang::Worker worker;
|
||||||
|
return worker.work();
|
||||||
|
}
|
||||||
|
|
||||||
|
// vim:set sts=2 sw=2 et:
|
||||||
|
|
Loading…
Add table
Reference in a new issue