In my application i have given sleep of 10 sec. I have given sleep using boost::this_thread::sleep function. Is there any possible way to interrupt boost::this_thread::sleep function.?
-
@WouterHuysentruit, should you answer beeing funny? – Nidhoegger May 29 '15 at 11:46
3 Answers
From the sleep()
reference:
Throws:
boost::thread_interrupted
if the current thread of execution is interrupted.Notes:
sleep()
is one of the predefined interruption points.
So what you need to do in your thread is to put the sleep()
call in a try-catch
, and catch boost::thread_interrupted
. Then call interrupt()
on the thread object to interrupt the sleep.
By the way, also from the sleep
reference:
Warning
DEPRECATED since 3.0.0.
Use
sleep_for()
andsleep_until()
instead.

- 400,186
- 35
- 402
- 621
-
hey @Joachim Pileborg i m using sleep function from "boost::this_thread" which does not have interrupt API and my requirement is to use "boost::this_thread" so is there any way to interrupt sleep. – Mukul May 29 '15 at 11:55
-
@user3721279 `boost::this_thread::sleep` is, as I quoted from the link in my answer, an *interruption* point. Please read the links provided in my answer. – Some programmer dude May 29 '15 at 12:27
You can interrupt the sleep
function using interrupt()
.
You have to enable interruption for your thread, when its sleeping, you can use the interrupt function.
Boost hast a very nice short tutorial online regarding this, have a look here: http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html#thread.thread_management.tutorial.interruption

- 4,973
- 4
- 36
- 81
I have given sleep using boost::this_thread::sleep function. Is there any possible way to interrupt boost::this_thread::sleep function.?
Not as such, but it is not difficult to implement it, in terms of boost::this_thread::sleep
:
void sleep_for(boost::posix_time::milliseconds interval, std::atomic<bool>& interrupted)
{
static const auto resolution = boost::posix_time::milliseconds(10));
ptime end_time(microsec_clock::local_time()) + interval;
while( !interrupted.load() )
{
boost::this_thread::sleep(resolution);
if(microsec_clock::local_time() > end_time)
break;
}
}
Client code thread 1:
std::atomic<bool>& interrupt = false;
void f() {
sleep_for(boost::posix_time::milliseconds(200), interrupt);
}
Client code thread 2:
interrupt.store(true); /// will cause thread 1 to be interrupted, if called
/// during execution of sleep_for.

- 26,809
- 3
- 46
- 82