How to sleep a C++ Boost Thread How to sleep a C++ Boost Thread multithreading multithreading

How to sleep a C++ Boost Thread


Depending on your version of Boost:

Either...

#include <boost/chrono.hpp>#include <boost/thread/thread.hpp> boost::this_thread::sleep_for(boost::chrono::milliseconds(100));

Or...

#include <boost/date_time/posix_time/posix_time.hpp>#include <boost/thread/thread.hpp> boost::this_thread::sleep(boost::posix_time::milliseconds(100));

You can also use microseconds, seconds, minutes, hours and maybe some others, I'm not sure.


From another post, I learned boost::this_thread::sleep is deprecated for Boost v1.5.3: http://www.boost.org/doc/libs/1_53_0/doc/html/thread/thread_management.html

Instead, try

void sleep_for(const chrono::duration<Rep, Period>& rel_time);

e.g.

boost::this_thread::sleep_for(boost::chrono::seconds(60));

Or maybe try

void sleep_until(const chrono::time_point<Clock, Duration>& abs_time);

I was using Boost v1.53 with the deprecated sleep function, and it aperiodically crashed the program. When I changed calls to the sleep function to calls to the sleep_for function, the program stopped crashing.


firstly

boost::posix_time::seconds secTime(1);  boost::this_thread::sleep(secTime); 

secondly

boost::this_thread::sleep(boost::posix_time::milliseconds(100));