Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- class MyBackground {
- public:
- MyBackground()
- {
- m_workerThread = std::thread(&MyBackground::work, this);
- }
- ~MyBackground()
- {
- g_exit = true;
- workerThread.join();
- }
- private:
- void work()
- {
- while(!m_exit);
- }
- private:
- std::atomic<bool> m_exit{false};
- std::thread m_workerThread;
- };
- int main(int argc, char* argv[])
- {
- MyBackground object;
- // here ther's some async background work
- return EXIT_SUCCESS;
- // ~MyBackground -> here threads are stopped
- }
- #include <csignal>
- #include <iostream>
- #include <thread>
- using namespace std
- atomic<bool> g_Exit{false};
- void signalExit(int)
- {
- g_Exit = true;
- }
- int main(int argc, char* argv[])
- {
- signal(SIGINT, signalExit);
- signal(SIGTERM, signalExit);
- MyBackground object;
- while (!g_Exit)
- this_thread::sleep_for(chrono::seconds{1});
- // here ther's some async background work
- return EXIT_SUCCESS;
- // ~MyBackground -> here threads are stopped
- }
- #include <csignal>
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- using namespace std
- bool g_exitFlag = false;
- condition_variable g_exitCondition;
- mutex g_exitMutex;
- using Lock = unique_lock<mutex>;
- void signalExit(int)
- {
- Lock lock{g_exitMutex};
- g_exitFlag = true;
- g_exitCondition.notify_one();
- }
- int main(int argc, char* argv[])
- {
- signal(SIGINT, signalExit);
- signal(SIGTERM, signalExit);
- MyBackground object;
- Lock lock{g_exitMutex};
- g_exitCondition.wait(lock, [](){return g_exitFlag;});
- // here ther's some async background work
- return EXIT_SUCCESS;
- // ~MyBackground -> here threads are stopped
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement