Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I exchange usleep by sleep_for

Tags:

c++

c++11

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.

like image 982
Claas Bontus Avatar asked Oct 01 '15 12:10

Claas Bontus


People also ask

What is the difference between sleep () and usleep () functions in Linux?

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.

What is the use of usleep?

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.

Does usleep return to the caller?

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.

Which header defines the sleep () function to suspend the execution of program?

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.


1 Answers

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).

like image 64
Andrew Avatar answered Oct 05 '22 17:10

Andrew