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.
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));
New answer for an old question:
Rationale for the new answer: Tools / OSs have been updated such that there is a better choice now than there was when the question was originally asked.
The C++11 <chrono>
and <thread>
std headers have been in the VS toolset for several years now. Using these headers this is best coded in C++11 as:
std::this_thread::sleep_for(std::chrono::microseconds(123));
I'm using microseconds only as an example duration. You can use whatever duration happens to be convenient:
std::this_thread::sleep_for(std::chrono::minutes(2));
With C++14 and some using directives, this can be written a little bit more compactly:
using namespace std::literals;
std::this_thread::sleep_for(2min);
or:
std::this_thread::sleep_for(123us);
This definitely works on VS-2013 (modulo the chrono-literals). I'm unsure about earlier versions of VS.