Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++, usleep() is obsolete, workarounds for Windows/MingW?

I already found out with another question that Windows/MingW doesn't provide the nanosleep() and setitimer() alternatives to the obsolete usleep(). But my goal is to fix all warnings that cppcheck gives me, including the usleep() style warnings.

So, is there a workaround to somehow avoid usleep() on Windows without using cygwin or installing loads of new dependencies/libraries? Thanks.

like image 999
blubberbernd Avatar asked Apr 27 '11 09:04

blubberbernd


People also ask

Does usleep work on windows?

It will work both on linux and on windows, i.e. it can be called using an uniform interface (the behavior can be still different especially on Windows where you can ask for 1 microsecond but you get 1ms sleep).

What is Usleep function in C?

The function usleep() is a C API that suspends the current process for the number of microseconds passed to it. It can be used for delaying a job. DLYJOB works well if you are looking to delay a job for more than a second. If you need to delay the job for less than a second, however, you must use the usleep() API.


1 Answers

I used this code from (originally from here):

#include <windows.h>  void usleep(__int64 usec)  {      HANDLE timer;      LARGE_INTEGER ft;       ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time      timer = CreateWaitableTimer(NULL, TRUE, NULL);      SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);      WaitForSingleObject(timer, INFINITE);      CloseHandle(timer);  } 

Note that SetWaitableTimer() uses "100 nanosecond intervals ... Positive values indicate absolute time. ... Negative values indicate relative time." and that "The actual timer accuracy depends on the capability of your hardware."

If you have a C++11 compiler then you can use this portable version:

#include <chrono> #include <thread> ... std::this_thread::sleep_for(std::chrono::microseconds(usec)); 

Kudos to Howard Hinnant who designed the amazing <chrono> library (and whose answer below deserves more love.)

If you don't have C++11, but you have boost, then you can do this instead:

#include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> ... boost::this_thread::sleep(boost::posix_time::microseconds(usec)); 
like image 179
Adi Shavit Avatar answered Oct 07 '22 16:10

Adi Shavit