#include #include #include #include //---------------------------------------------------------------------------- class MyControl { public: MyControl (void) : m_mutex(), m_stopCommanded(false) {} void stop (void) { boost::mutex::scoped_lock lock(m_mutex); m_stopCommanded = true; } bool stopWasCommanded (void) const { boost::mutex::scoped_lock lock(m_mutex); return m_stopCommanded; } private: mutable boost::mutex m_mutex; bool m_stopCommanded; }; //---------------------------------------------------------------------------- class MyThreadFunctor { public: explicit MyThreadFunctor (MyControl& control) : m_control(control) {} void operator() (void) { std::cerr << "MyThreadFunctor started" << std::endl; int counter = 0; while (!m_control.stopWasCommanded()) { std::cerr << "MyThreadFunctor running" << std::endl; // Sleep for a second boost::xtime expiration; boost::xtime_get(&expiration, boost::TIME_UTC); expiration.sec += 1; boost::thread::sleep(expiration); } std::cerr << "MyThreadFunctor stopped" << std::endl; } private: MyControl& m_control; }; //---------------------------------------------------------------------------- int main (void) { MyControl control; // Start the thread MyThreadFunctor functor(control); boost::thread t(functor); // Main thread logic (sleep for 5 seconds) boost::xtime expiration; boost::xtime_get(&expiration, boost::TIME_UTC); expiration.sec += 5; boost::thread::sleep(expiration); std::cerr << "Main thread logic is done" << std::endl; // Command the thread to stop control.stop(); // Wait for the thread to exit t.join(); return 0; }