How to sleep a C++ Boost Thread

Andry picture Andry · Nov 24, 2010 · Viewed 65.8k times · Source

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

Answer

Benjamin Lindley picture Benjamin Lindley · Nov 24, 2010

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.