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