Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sleep a C++ Boost Thread

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

like image 838
Andry Avatar asked Nov 24 '10 09:11

Andry


People also ask

How do I stop a boost thread?

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.

How do I sleep a thread in CPP?

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.

Does sleep block the thread?

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.

What are sleeping threads?

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.


2 Answers

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.

like image 57
Benjamin Lindley Avatar answered Sep 17 '22 20:09

Benjamin Lindley


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.

like image 31
user3731622 Avatar answered Sep 17 '22 20:09

user3731622