The usleep() emulation on MSVC has a resolution of 1 second only. This patch improves it, to have a resolution of 15 milliseconds.
2019-07-02 Bruno Haible <br...@clisp.org> usleep: Implement with millisecond resolution on native Windows. * lib/usleep.c (usleep): On native Windows, implement using Sleep(). * doc/pastposix-functions/usleep.texi: Update accordingly. diff --git a/doc/pastposix-functions/usleep.texi b/doc/pastposix-functions/usleep.texi index 440a00e..14de4b2 100644 --- a/doc/pastposix-functions/usleep.texi +++ b/doc/pastposix-functions/usleep.texi @@ -16,7 +16,7 @@ mingw. This function is missing on some platforms. However, the replacement is designed to be lightweight, and may round to the nearest second; use @code{select} or @code{nanosleep} if better resolution is needed: -IRIX 5.3, Solaris 2.4, older mingw, MSVC 14, BeOS. +IRIX 5.3, Solaris 2.4, BeOS. @end itemize Portability problems not fixed by Gnulib: diff --git a/lib/usleep.c b/lib/usleep.c index f7e2480..480605f 100644 --- a/lib/usleep.c +++ b/lib/usleep.c @@ -28,6 +28,11 @@ #include <errno.h> +#if defined _WIN32 && ! defined __CYGWIN__ +# define WIN32_LEAN_AND_MEAN /* avoid including junk */ +# include <windows.h> +#endif + #ifndef HAVE_USLEEP # define HAVE_USLEEP 0 #endif @@ -39,7 +44,20 @@ int usleep (useconds_t micro) +#undef usleep { +#if defined _WIN32 && ! defined __CYGWIN__ + unsigned int milliseconds = micro / 1000; + if (sizeof milliseconds < sizeof micro && micro / 1000 != milliseconds) + { + errno = EINVAL; + return -1; + } + if (micro % 1000) + milliseconds++; + Sleep (milliseconds); + return 0; +#else unsigned int seconds = micro / 1000000; if (sizeof seconds < sizeof micro && micro / 1000000 != seconds) { @@ -50,9 +68,9 @@ usleep (useconds_t micro) seconds++; while ((seconds = sleep (seconds)) != 0); -#undef usleep -#if !HAVE_USLEEP -# define usleep(x) 0 -#endif +# if !HAVE_USLEEP +# define usleep(x) 0 +# endif return usleep (micro % 1000000); +#endif }