File: usleep.h

package info (click to toggle)
o2 1.0~repack-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 1,156 kB
  • sloc: ansic: 9,132; python: 137; sh: 111; makefile: 10
file content (41 lines) | stat: -rw-r--r-- 1,333 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* usleep.h -- implement a substitute for usleep and sleep on windows
 *
 * Roger Dannenberg   Jan 2017
 *
 * I tried #define usleep(x) Sleep((x)/1000)
 * thinking that Sleep() would give ms delays and that would be good
 * enough, but in a loop that calls usleep(2000) 500 times, which
 * should nominally delay 1s, the delay could be 7s or more. I just
 * want to call o2_poll() while delaying. What I will try is to 
 * keep track of cummulative *intended* delay and return immediately
 * if we're seeing that delay already.
 *
 * This file can just be included -- it's used in a lot of test
 * programs which all have one source file that links to O2. It
 * seems unnecessary to create a separate object file to link and
 * then have system dependent link instructions.
 */

#include <windows.h>
#include <timeapi.h>

long last_time = 0;
long long implied_wakeup_us = 0;
void usleep(long usec)
{
    long now = timeGetTime();
    if (now - last_time < 50) {
        // assume the intention is a sequence of short delays
        implied_wakeup_us += usec;
    } else { // a long time has elapsed
        implied_wakeup_us = now * 1000LL + usec;
    }
    long wake_ms = (int) (implied_wakeup_us / 1000);
    if (wake_ms > now + 1) Sleep(wake_ms - now);
    last_time = wake_ms;
}

void sleep(int secs)
{
    Sleep(secs * 1000);
}