I am in the stage of upgrading some legacy C++ code to C++11 under Linux using gcc. When trying to set priorities I came up with the following question. Could there be any advantage in exchanging a call to usleep
with a call to std::this_thread::sleep_for
? In the code I am talking about the running thread is supposed to wait for a very short period. Therefore I don't need any advanced features like interrupting the sleep.
The sleep () function accepts time in seconds while usleep () accepts in microseconds. The source code to demonstrate sleep () and usleep () functions for the linux operating system is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
The usleep () function suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.
If an incoming unblocked signal has an action of end the request or terminate the process, usleep () never returns to the caller. If an incoming signal is handled by a signal-catching function, usleep () returns after the signal-catching function returns.
Answer: The header ‘Unistd.h’ is the header that defines the sleep () function to suspend the execution of the program. In this tutorial for sleep () function, we have discussed the sleep function and usleep () function which is the same as the sleep and thread sleep functions, sleep_for and sleep_until.
Yes. std::this_thread::sleep_for
is specified by the C++11 standard, and is therefore a portable solution on any system with a C++11 compiler and standard library.
usleep
is specified by POSIX.1-2001 (and declared obsolete!), which means it can only be (reliably) used on POSIX compliant systems.
POSIX.1-2008 removes the specification of usleep
, in favour of nanosleep
. For this reason alone, std::this_thread::sleep_for
is a much better choice.
(See http://linux.die.net/man/3/usleep for details).
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