sleep.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <windows.h>
  27. #include <errno.h>
  28. #include <limits.h>
  29. HANDLE waitTimer = NULL;
  30. void init_sleep(void) {
  31. waitTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  32. }
  33. void deinit_sleep(void) {
  34. if (waitTimer != NULL) {
  35. CloseHandle(waitTimer);
  36. waitTimer = NULL;
  37. }
  38. }
  39. int usleep_impl(__int64 usec) {
  40. if (waitTimer == NULL) {
  41. errno = EAGAIN;
  42. return -1;
  43. }
  44. if (usec < 0 || usec > LLONG_MAX / 10) {
  45. errno = EINVAL;
  46. return -1;
  47. }
  48. LARGE_INTEGER ft;
  49. ft.QuadPart = -10 * usec; // 100 nanosecond interval, negative value = relative time
  50. if (SetWaitableTimer(waitTimer, &ft, 0, NULL, NULL, 0) == 0) {
  51. errno = EINVAL;
  52. return -1;
  53. }
  54. if (WaitForSingleObject(waitTimer, INFINITE) != WAIT_OBJECT_0) {
  55. errno = EAGAIN;
  56. return -1;
  57. }
  58. return 0;
  59. }
  60. #ifdef _MSC_VER // mingw and the likes provide their own usleep()
  61. int usleep(__int64 usec) {
  62. return usleep_impl(usec);
  63. }
  64. #endif
  65. void msec_sleep(double msec) {
  66. const double usec = msec * 1000.0;
  67. usleep_impl(usec > (double)LLONG_MAX ? LLONG_MAX : (__int64)usec);
  68. }