example: prefer helper methods

This commit is contained in:
Tom 2020-07-18 00:20:54 +02:00
parent 6382be9907
commit 562a037c39

View File

@ -2,22 +2,16 @@
#include <sgnl/SignalHandler.h> #include <sgnl/SignalHandler.h>
#include <cstdlib> #include <cstdlib>
#include <future>
#include <iostream> #include <iostream>
#include <thread>
void Worker(const sgnl::AtomicCondition<bool>& exit_condition) void Worker(const sgnl::AtomicCondition<bool>& exit_condition)
{ {
auto predicate = [&exit_condition]() { while( !exit_condition.get() )
return exit_condition.get();
};
while( true )
{ {
exit_condition.wait_for(std::chrono::minutes(1), predicate);
if( exit_condition.get() )
return;
/* ... do work ... */ /* ... do work ... */
exit_condition.wait_for_value(true, std::chrono::minutes(1));
} }
} }
@ -25,13 +19,13 @@ int main()
{ {
sgnl::AtomicCondition<bool> exit_condition(false); sgnl::AtomicCondition<bool> exit_condition(false);
auto handler = [&exit_condition](int signum) { auto my_handler = [&exit_condition](int signum) {
std::cout << "received signal " << signum << "\n"; std::cout << "received signal " << signum << "\n";
if( signum == SIGTERM || signum == SIGINT ) if( signum == SIGTERM || signum == SIGINT )
{ {
exit_condition.set(true); // set atomic<bool> and wakeup all waiting threads
// wakeup all waiting threads exit_condition.set_and_notify_all(true);
exit_condition.notify_all();
// stop polling for signals // stop polling for signals
return true; return true;
} }
@ -45,11 +39,9 @@ int main()
sgnl::SignalHandler signal_handler({SIGINT, SIGTERM, SIGUSR1}); sgnl::SignalHandler signal_handler({SIGINT, SIGTERM, SIGUSR1});
std::future<int> ft_sig_handler = std::future<int> ft_sig_handler =
std::async( // Spawn a thread that handles the
std::launch::async, // signals {SIGINT, SIGTERM, SIGUSR1}
&sgnl::SignalHandler::sigwait_handler, signal_handler.async_sigwait_handler(my_handler);
&signal_handler,
std::ref(handler));
std::vector<std::future<void>> futures; std::vector<std::future<void>> futures;
for(int i = 0; i < 10; ++i) for(int i = 0; i < 10; ++i)