Seems impossible to sleep a thread using boost::thread. Method sleep requires a system_time but how can I build it?
Looking inside libraries doesn't really help much...
Basically I have a thread inside the function that I pass to this thread as entry point, I would like to call something like
boost::this_thread::sleep
or something, how to do this?
Thank you
A running thread can be interrupted by calling the interrupt() member function on the corresponding boost::thread object. If the thread doesn't have a boost::thread object (e.g the initial thread of the application), then it cannot be interrupted.
Thread Sleep (sleep_for & sleep_until) C++ 11 provides specific functions to put a thread to sleep. Description: The sleep_for () function is defined in the header <thread>. The sleep_for () function blocks the execution of the current thread at least for the specified time i.e. sleep_duration.
We now understand that we cannot use Thread. sleep – it blocks the thread. This makes it unusable until it resumes, preventing us from running 2 tasks concurrently.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With