Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::this_thread::sleep_for behaviour defined for signal interupt ( or signal handler) in C++11?

Tags:

c++

linux

The behavior of sleep() in unistd.h is well defined in Linux http://man7.org/linux/man-pages/man3/sleep.3.html.

Questions:

  1. Does the C++11 standard define the behavior of std::this_thread::sleep_for for signal interrupt/signal handler? If yes, is the behavior platform dependent? (I hope not)

  2. What is the best approach to implement non-interuptable sleep() in Linux? Based on my knowledge this can be done by blocking all the signals before calling the sleep().

like image 548
Zhongkun Ma Avatar asked Aug 31 '25 18:08

Zhongkun Ma


1 Answers

Does the C++11 standard define the behavior of std::this_thread::sleep_for for signal interrupt/signal handler?

No.

is the behavior platform dependent?

Since it's unspecified, it can be.

I tested on linux, and a signal did interrupt the sleep prematurely.

What is the best approach to implement non-interuptable sleep() in Linux?

A best practice is to not need a non-interruptable sleep. sleep returns the time left to sleep if it is interrupted, so to prevent premature wakeup, you can simply resume sleep after interruption using a loop:

int time = 10;
while(time = sleep(time));

Unfortunately, that's not the case with this_thread::sleep_for which doesn't return the time left upon interruption.

like image 95
eerorika Avatar answered Sep 02 '25 07:09

eerorika