summaryrefslogtreecommitdiff
path: root/rts/win32/Ticker.c
blob: 7bc5ed55e3c8c9ae58d5ea246f944d11e91a867e (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
 * RTS periodic timers.
 *
 */

#include "Rts.h"
#include "Ticker.h"
#include <windows.h>
#include <stdio.h>
#include <process.h>

static TickProc tick_proc = NULL;
static HANDLE timer_queue = NULL;
static HANDLE timer       = NULL;
static Time tick_interval = 0;

static VOID CALLBACK tick_callback(
  PVOID lpParameter STG_UNUSED,
  BOOLEAN TimerOrWaitFired STG_UNUSED
  )
{
    tick_proc(0);
}

// We use the CreateTimerQueue() API which has been around since
// Windows 2000.  Apparently it gives bad results before Windows 7,
// though: http://www.virtualdub.org/blog/pivot/entry.php?id=272
//
// Even with the improvements in Windows 7, this timer isn't going to
// be very useful for profiling with a max usable resolution of
// 15ms. Unfortunately we don't have anything better.

void
initTicker (Time interval, TickProc handle_tick)
{
    tick_interval = interval;
    tick_proc = handle_tick;

    timer_queue = CreateTimerQueue();
    if (timer_queue == NULL) {
        sysErrorBelch("CreateTimerQueue");
        stg_exit(EXIT_FAILURE);
    }
}

void
startTicker(void)
{
    BOOL r;

    r = CreateTimerQueueTimer(&timer,
                              timer_queue,
                              tick_callback,
                              0,
                              0,
                              TimeToUS(tick_interval) / 1000, // ms
                              WT_EXECUTEINTIMERTHREAD);
    if (r == 0) {
        sysErrorBelch("CreateTimerQueueTimer");
        stg_exit(EXIT_FAILURE);
    }
}

void
stopTicker(void)
{
    if (timer_queue != NULL && timer != NULL) {
        DeleteTimerQueueTimer(timer_queue, timer, NULL);
        timer = NULL;
    }
}

void
exitTicker (bool wait)
{
    if (timer_queue != NULL) {
        DeleteTimerQueueEx(timer_queue, wait ? INVALID_HANDLE_VALUE : NULL);
        timer_queue = NULL;
    }
}