blob: 29641654c57e8bd748afc550fc7a2928a6d788c7 [file] [log] [blame]
Kristján Valur Jónssone75ff352012-06-18 20:30:44 +00001/*
2 * Portable condition variable support for windows and pthreads.
3 * Everything is inline, this header can be included where needed.
4 *
5 * APIs generally return 0 on success and non-zero on error,
6 * and the caller needs to use its platform's error mechanism to
7 * discover the error (errno, or GetLastError())
8 *
9 * Note that some implementations cannot distinguish between a
10 * condition variable wait time-out and successful wait. Most often
11 * the difference is moot anyway since the wait condition must be
12 * re-checked.
13 * PyCOND_TIMEDWAIT, in addition to returning negative on error,
14 * thus returns 0 on regular success, 1 on timeout
15 * or 2 if it can't tell.
16 */
17
18#ifndef _CONDVAR_H_
19#define _CONDVAR_H_
20
21#include "Python.h"
22
23#ifndef _POSIX_THREADS
24/* This means pthreads are not implemented in libc headers, hence the macro
25 not present in unistd.h. But they still can be implemented as an external
26 library (e.g. gnu pth in pthread emulation) */
27# ifdef HAVE_PTHREAD_H
28# include <pthread.h> /* _POSIX_THREADS */
29# endif
30#endif
31
32#ifdef _POSIX_THREADS
33/*
34 * POSIX support
35 */
36#define Py_HAVE_CONDVAR
37
38#include <pthread.h>
39
40#define PyCOND_ADD_MICROSECONDS(tv, interval) \
41do { \
42 tv.tv_usec += (long) interval; \
43 tv.tv_sec += tv.tv_usec / 1000000; \
44 tv.tv_usec %= 1000000; \
45} while (0)
46
47/* We assume all modern POSIX systems have gettimeofday() */
48#ifdef GETTIMEOFDAY_NO_TZ
49#define PyCOND_GETTIMEOFDAY(ptv) gettimeofday(ptv)
50#else
51#define PyCOND_GETTIMEOFDAY(ptv) gettimeofday(ptv, (struct timezone *)NULL)
52#endif
53
54/* The following functions return 0 on success, nonzero on error */
55#define PyMUTEX_T pthread_mutex_t
56#define PyMUTEX_INIT(mut) pthread_mutex_init((mut), NULL)
57#define PyMUTEX_FINI(mut) pthread_mutex_destroy(mut)
58#define PyMUTEX_LOCK(mut) pthread_mutex_lock(mut)
59#define PyMUTEX_UNLOCK(mut) pthread_mutex_unlock(mut)
60
61#define PyCOND_T pthread_cond_t
62#define PyCOND_INIT(cond) pthread_cond_init((cond), NULL)
63#define PyCOND_FINI(cond) pthread_cond_destroy(cond)
64#define PyCOND_SIGNAL(cond) pthread_cond_signal(cond)
65#define PyCOND_BROADCAST(cond) pthread_cond_broadcast(cond)
66#define PyCOND_WAIT(cond, mut) pthread_cond_wait((cond), (mut))
67
68/* return 0 for success, 1 on timeout, -1 on error */
69Py_LOCAL_INLINE(int)
70PyCOND_TIMEDWAIT(PyCOND_T *cond, PyMUTEX_T *mut, long us)
71{
72 int r;
73 struct timespec ts;
74 struct timeval deadline;
75
76 PyCOND_GETTIMEOFDAY(&deadline);
77 PyCOND_ADD_MICROSECONDS(deadline, us);
78 ts.tv_sec = deadline.tv_sec;
79 ts.tv_nsec = deadline.tv_usec * 1000;
80
81 r = pthread_cond_timedwait((cond), (mut), &ts);
82 if (r == ETIMEDOUT)
83 return 1;
84 else if (r)
85 return -1;
86 else
87 return 0;
88}
89
90#elif defined(NT_THREADS)
91/*
92 * Windows (XP, 2003 server and later, as well as (hopefully) CE) support
93 *
94 * Emulated condition variables ones that work with XP and later, plus
95 * example native support on VISTA and onwards.
96 */
97#define Py_HAVE_CONDVAR
98
99
100/* include windows if it hasn't been done before */
101#define WIN32_LEAN_AND_MEAN
102#include <windows.h>
103
104/* options */
105/* non-emulated condition variables are provided for those that want
106 * to target Windows Vista. Modify this macro to enable them.
107 */
108#ifndef _PY_EMULATED_WIN_CV
109#define _PY_EMULATED_WIN_CV 1 /* use emulated condition variables */
110#endif
111
112/* fall back to emulation if not targeting Vista */
113#if !defined NTDDI_VISTA || NTDDI_VERSION < NTDDI_VISTA
114#undef _PY_EMULATED_WIN_CV
115#define _PY_EMULATED_WIN_CV 1
116#endif
117
118
119#if _PY_EMULATED_WIN_CV
120
121/* The mutex is a CriticalSection object and
122 The condition variables is emulated with the help of a semaphore.
123 Semaphores are available on Windows XP (2003 server) and later.
124 We use a Semaphore rather than an auto-reset event, because although
125 an auto-resent event might appear to solve the lost-wakeup bug (race
126 condition between releasing the outer lock and waiting) because it
127 maintains state even though a wait hasn't happened, there is still
128 a lost wakeup problem if more than one thread are interrupted in the
129 critical place. A semaphore solves that, because its state is counted,
130 not Boolean.
131 Because it is ok to signal a condition variable with no one
132 waiting, we need to keep track of the number of
133 waiting threads. Otherwise, the semaphore's state could rise
134 without bound. This also helps reduce the number of "spurious wakeups"
135 that would otherwise happen.
136
137 Generic emulations of the pthread_cond_* API using
138 earlier Win32 functions can be found on the Web.
139 The following read can be edificating (or not):
140 http://www.cse.wustl.edu/~schmidt/win32-cv-1.html
141*/
142
143typedef CRITICAL_SECTION PyMUTEX_T;
144
145Py_LOCAL_INLINE(int)
146PyMUTEX_INIT(PyMUTEX_T *cs)
147{
148 InitializeCriticalSection(cs);
149 return 0;
150}
151
152Py_LOCAL_INLINE(int)
153PyMUTEX_FINI(PyMUTEX_T *cs)
154{
155 DeleteCriticalSection(cs);
156 return 0;
157}
158
159Py_LOCAL_INLINE(int)
160PyMUTEX_LOCK(PyMUTEX_T *cs)
161{
162 EnterCriticalSection(cs);
163 return 0;
164}
165
166Py_LOCAL_INLINE(int)
167PyMUTEX_UNLOCK(PyMUTEX_T *cs)
168{
169 LeaveCriticalSection(cs);
170 return 0;
171}
172
173/* The ConditionVariable object. From XP onwards it is easily emulated with
174 * a Semaphore
175 */
176
177typedef struct _PyCOND_T
178{
179 HANDLE sem;
Kristjan Valur Jonsson16170772012-06-19 10:10:09 +0000180 int waiting; /* to allow PyCOND_SIGNAL to be a no-op */
Kristján Valur Jónssone75ff352012-06-18 20:30:44 +0000181} PyCOND_T;
182
183Py_LOCAL_INLINE(int)
184PyCOND_INIT(PyCOND_T *cv)
185{
186 /* A semaphore with a "large" max value, The positive value
187 * is only needed to catch those "lost wakeup" events and
188 * race conditions when a timed wait elapses.
189 */
190 cv->sem = CreateSemaphore(NULL, 0, 100000, NULL);
191 if (cv->sem==NULL)
192 return -1;
193 cv->waiting = 0;
194 return 0;
195}
196
197Py_LOCAL_INLINE(int)
198PyCOND_FINI(PyCOND_T *cv)
199{
200 return CloseHandle(cv->sem) ? 0 : -1;
201}
202
203/* this implementation can detect a timeout. Returns 1 on timeout,
204 * 0 otherwise (and -1 on error)
205 */
206Py_LOCAL_INLINE(int)
207_PyCOND_WAIT_MS(PyCOND_T *cv, PyMUTEX_T *cs, DWORD ms)
208{
209 DWORD wait;
210 cv->waiting++;
211 PyMUTEX_UNLOCK(cs);
212 /* "lost wakeup bug" would occur if the caller were interrupted here,
213 * but we are safe because we are using a semaphore wich has an internal
214 * count.
215 */
216 wait = WaitForSingleObject(cv->sem, ms);
217 PyMUTEX_LOCK(cs);
218 if (wait != WAIT_OBJECT_0)
219 --cv->waiting;
220 /* Here we have a benign race condition with PyCOND_SIGNAL.
221 * When failure occurs or timeout, it is possible that
222 * PyCOND_SIGNAL also decrements this value
223 * and signals releases the mutex. This is benign because it
224 * just means an extra spurious wakeup for a waiting thread.
Kristjan Valur Jonsson16170772012-06-19 10:10:09 +0000225 * ('waiting' corresponds to the semaphore's "negative" count and
226 * we may end up with e.g. (waiting == -1 && sem.count == 1). When
227 * a new thread comes along, it will pass right throuhgh, having
228 * adjusted it to (waiting == 0 && sem.count == 0).
Kristján Valur Jónssone75ff352012-06-18 20:30:44 +0000229 */
230
231 if (wait == WAIT_FAILED)
232 return -1;
233 /* return 0 on success, 1 on timeout */
234 return wait != WAIT_OBJECT_0;
235}
236
237Py_LOCAL_INLINE(int)
238PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs)
239{
240 int result = _PyCOND_WAIT_MS(cv, cs, INFINITE);
241 return result >= 0 ? 0 : result;
242}
243
244Py_LOCAL_INLINE(int)
245PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long us)
246{
247 return _PyCOND_WAIT_MS(cv, cs, us/1000);
248}
249
250Py_LOCAL_INLINE(int)
251PyCOND_SIGNAL(PyCOND_T *cv)
252{
Kristjan Valur Jonsson16170772012-06-19 10:10:09 +0000253 /* this test allows PyCOND_SIGNAL to be a no-op unless required
254 * to wake someone up, thus preventing an unbounded increase of
255 * the semaphore's internal counter.
256 */
257 if (cv->waiting > 0) {
Kristján Valur Jónssone75ff352012-06-18 20:30:44 +0000258 /* notifying thread decreases the cv->waiting count so that
Kristjan Valur Jonsson16170772012-06-19 10:10:09 +0000259 * a delay between notify and actual wakeup of the target thread
260 * doesn't cause a number of extra ReleaseSemaphore calls.
Kristján Valur Jónssone75ff352012-06-18 20:30:44 +0000261 */
262 cv->waiting--;
263 return ReleaseSemaphore(cv->sem, 1, NULL) ? 0 : -1;
264 }
265 return 0;
266}
267
268Py_LOCAL_INLINE(int)
269PyCOND_BROADCAST(PyCOND_T *cv)
270{
Kristjan Valur Jonsson16170772012-06-19 10:10:09 +0000271 if (cv->waiting > 0) {
Kristján Valur Jónssone75ff352012-06-18 20:30:44 +0000272 return ReleaseSemaphore(cv->sem, cv->waiting, NULL) ? 0 : -1;
273 cv->waiting = 0;
274 }
275 return 0;
276}
277
278#else
279
280/* Use native Win7 primitives if build target is Win7 or higher */
281
282/* SRWLOCK is faster and better than CriticalSection */
283typedef SRWLOCK PyMUTEX_T;
284
285Py_LOCAL_INLINE(int)
286PyMUTEX_INIT(PyMUTEX_T *cs)
287{
288 InitializeSRWLock(cs);
289 return 0;
290}
291
292Py_LOCAL_INLINE(int)
293PyMUTEX_FINI(PyMUTEX_T *cs)
294{
295 return 0;
296}
297
298Py_LOCAL_INLINE(int)
299PyMUTEX_LOCK(PyMUTEX_T *cs)
300{
301 AcquireSRWLockExclusive(cs);
302 return 0;
303}
304
305Py_LOCAL_INLINE(int)
306PyMUTEX_UNLOCK(PyMUTEX_T *cs)
307{
308 ReleaseSRWLockExclusive(cs);
309 return 0;
310}
311
312
313typedef CONDITION_VARIABLE PyCOND_T;
314
315Py_LOCAL_INLINE(int)
316PyCOND_INIT(PyCOND_T *cv)
317{
318 InitializeConditionVariable(cv);
319 return 0;
320}
321Py_LOCAL_INLINE(int)
322PyCOND_FINI(PyCOND_T *cv)
323{
324 return 0;
325}
326
327Py_LOCAL_INLINE(int)
328PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs)
329{
330 return SleepConditionVariableSRW(cv, cs, INFINITE, 0) ? 0 : -1;
331}
332
333/* This implementation makes no distinction about timeouts. Signal
334 * 2 to indicate that we don't know.
335 */
336Py_LOCAL_INLINE(int)
337PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long us)
338{
339 return SleepConditionVariableSRW(cv, cs, us/1000, 0) ? 2 : -1;
340}
341
342Py_LOCAL_INLINE(int)
343PyCOND_SIGNAL(PyCOND_T *cv)
344{
345 WakeConditionVariable(cv);
346 return 0;
347}
348
349Py_LOCAL_INLINE(int)
350PyCOND_BROADCAST(PyCOND_T *cv)
351{
352 WakeAllConditionVariable(cv);
353 return 0;
354}
355
356
357#endif /* _PY_EMULATED_WIN_CV */
358
359#endif /* _POSIX_THREADS, NT_THREADS */
360
361#endif /* _CONDVAR_H_ */