1 /*-------------------------------------------------------------------------
4 * Microsoft Windows Win32 Timer Implementation
6 * Limitations of this implementation:
8 * - Does not support interval timer (value->it_interval)
9 * - Only supports ITIMER_REAL
11 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
14 * $PostgreSQL: pgsql/src/backend/port/win32/timer.c,v 1.8 2006/03/05 15:58:35 momjian Exp $
16 *-------------------------------------------------------------------------
21 #include "libpq/pqsignal.h"
24 /* Communication area for inter-thread communication */
25 typedef struct timerCA
27 struct itimerval value;
29 CRITICAL_SECTION crit_sec;
32 static timerCA timerCommArea;
33 static HANDLE timerThreadHandle = INVALID_HANDLE_VALUE;
36 /* Timer management thread */
38 pg_timer_thread(LPVOID param)
42 Assert(param == NULL);
50 r = WaitForSingleObjectEx(timerCommArea.event, waittime, FALSE);
51 if (r == WAIT_OBJECT_0)
53 /* Event signalled from main thread, change the timer */
54 EnterCriticalSection(&timerCommArea.crit_sec);
55 if (timerCommArea.value.it_value.tv_sec == 0 &&
56 timerCommArea.value.it_value.tv_usec == 0)
57 waittime = INFINITE; /* Cancel the interrupt */
59 waittime = timerCommArea.value.it_value.tv_usec / 10 + timerCommArea.value.it_value.tv_sec * 1000;
60 ResetEvent(timerCommArea.event);
61 LeaveCriticalSection(&timerCommArea.crit_sec);
63 else if (r == WAIT_TIMEOUT)
65 /* Timeout expired, signal SIGALRM and turn it off */
66 pg_queue_signal(SIGALRM);
71 /* Should never happen */
80 * Win32 setitimer emulation by creating a persistent thread
81 * to handle the timer setting and notification upon timeout.
84 setitimer(int which, const struct itimerval * value, struct itimerval * ovalue)
86 Assert(value != NULL);
87 Assert(value->it_interval.tv_sec == 0 && value->it_interval.tv_usec == 0);
88 Assert(which == ITIMER_REAL);
90 if (timerThreadHandle == INVALID_HANDLE_VALUE)
92 /* First call in this backend, create event and the timer thread */
93 timerCommArea.event = CreateEvent(NULL, TRUE, FALSE, NULL);
94 if (timerCommArea.event == NULL)
96 (errmsg_internal("failed to create timer event: %d",
97 (int) GetLastError())));
99 MemSet(&timerCommArea.value, 0, sizeof(struct itimerval));
101 InitializeCriticalSection(&timerCommArea.crit_sec);
103 timerThreadHandle = CreateThread(NULL, 0, pg_timer_thread, NULL, 0, NULL);
104 if (timerThreadHandle == INVALID_HANDLE_VALUE)
106 (errmsg_internal("failed to create timer thread: %d",
107 (int) GetLastError())));
110 /* Request the timer thread to change settings */
111 EnterCriticalSection(&timerCommArea.crit_sec);
113 *ovalue = timerCommArea.value;
114 timerCommArea.value = *value;
115 LeaveCriticalSection(&timerCommArea.crit_sec);
116 SetEvent(timerCommArea.event);