You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

390 lines
11 KiB

  1. /*
  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. * There are at least two caveats with using these condition variables,
  18. * due to the fact that they may be emulated with Semaphores on
  19. * Windows:
  20. * 1) While PyCOND_SIGNAL() will wake up at least one thread, we
  21. * cannot currently guarantee that it will be one of the threads
  22. * already waiting in a PyCOND_WAIT() call. It _could_ cause
  23. * the wakeup of a subsequent thread to try a PyCOND_WAIT(),
  24. * including the thread doing the PyCOND_SIGNAL() itself.
  25. * The same applies to PyCOND_BROADCAST(), if N threads are waiting
  26. * then at least N threads will be woken up, but not necessarily
  27. * those already waiting.
  28. * For this reason, don't make the scheduling assumption that a
  29. * specific other thread will get the wakeup signal
  30. * 2) The _mutex_ must be held when calling PyCOND_SIGNAL() and
  31. * PyCOND_BROADCAST().
  32. * While e.g. the posix standard strongly recommends that the mutex
  33. * associated with the condition variable is held when a
  34. * pthread_cond_signal() call is made, this is not a hard requirement,
  35. * although scheduling will not be "reliable" if it isn't. Here
  36. * the mutex is used for internal synchronization of the emulated
  37. * Condition Variable.
  38. */
  39. #ifndef _CONDVAR_H_
  40. #define _CONDVAR_H_
  41. #include "Python.h"
  42. #ifndef _POSIX_THREADS
  43. /* This means pthreads are not implemented in libc headers, hence the macro
  44. not present in unistd.h. But they still can be implemented as an external
  45. library (e.g. gnu pth in pthread emulation) */
  46. # ifdef HAVE_PTHREAD_H
  47. # include <pthread.h> /* _POSIX_THREADS */
  48. # endif
  49. #endif
  50. #ifdef _POSIX_THREADS
  51. /*
  52. * POSIX support
  53. */
  54. #define Py_HAVE_CONDVAR
  55. #include <pthread.h>
  56. #define PyCOND_ADD_MICROSECONDS(tv, interval) \
  57. do { /* TODO: add overflow and truncation checks */ \
  58. tv.tv_usec += (long) interval; \
  59. tv.tv_sec += tv.tv_usec / 1000000; \
  60. tv.tv_usec %= 1000000; \
  61. } while (0)
  62. /* We assume all modern POSIX systems have gettimeofday() */
  63. #ifdef GETTIMEOFDAY_NO_TZ
  64. #define PyCOND_GETTIMEOFDAY(ptv) gettimeofday(ptv)
  65. #else
  66. #define PyCOND_GETTIMEOFDAY(ptv) gettimeofday(ptv, (struct timezone *)NULL)
  67. #endif
  68. /* The following functions return 0 on success, nonzero on error */
  69. #define PyMUTEX_T pthread_mutex_t
  70. #define PyMUTEX_INIT(mut) pthread_mutex_init((mut), NULL)
  71. #define PyMUTEX_FINI(mut) pthread_mutex_destroy(mut)
  72. #define PyMUTEX_LOCK(mut) pthread_mutex_lock(mut)
  73. #define PyMUTEX_UNLOCK(mut) pthread_mutex_unlock(mut)
  74. #define PyCOND_T pthread_cond_t
  75. #define PyCOND_INIT(cond) pthread_cond_init((cond), NULL)
  76. #define PyCOND_FINI(cond) pthread_cond_destroy(cond)
  77. #define PyCOND_SIGNAL(cond) pthread_cond_signal(cond)
  78. #define PyCOND_BROADCAST(cond) pthread_cond_broadcast(cond)
  79. #define PyCOND_WAIT(cond, mut) pthread_cond_wait((cond), (mut))
  80. /* return 0 for success, 1 on timeout, -1 on error */
  81. Py_LOCAL_INLINE(int)
  82. PyCOND_TIMEDWAIT(PyCOND_T *cond, PyMUTEX_T *mut, long long us)
  83. {
  84. int r;
  85. struct timespec ts;
  86. struct timeval deadline;
  87. PyCOND_GETTIMEOFDAY(&deadline);
  88. PyCOND_ADD_MICROSECONDS(deadline, us);
  89. ts.tv_sec = deadline.tv_sec;
  90. ts.tv_nsec = deadline.tv_usec * 1000;
  91. r = pthread_cond_timedwait((cond), (mut), &ts);
  92. if (r == ETIMEDOUT)
  93. return 1;
  94. else if (r)
  95. return -1;
  96. else
  97. return 0;
  98. }
  99. #elif defined(NT_THREADS)
  100. /*
  101. * Windows (XP, 2003 server and later, as well as (hopefully) CE) support
  102. *
  103. * Emulated condition variables ones that work with XP and later, plus
  104. * example native support on VISTA and onwards.
  105. */
  106. #define Py_HAVE_CONDVAR
  107. /* include windows if it hasn't been done before */
  108. #define WIN32_LEAN_AND_MEAN
  109. #include <windows.h>
  110. /* options */
  111. /* non-emulated condition variables are provided for those that want
  112. * to target Windows Vista. Modify this macro to enable them.
  113. */
  114. #ifndef _PY_EMULATED_WIN_CV
  115. #define _PY_EMULATED_WIN_CV 1 /* use emulated condition variables */
  116. #endif
  117. /* fall back to emulation if not targeting Vista */
  118. #if !defined NTDDI_VISTA || NTDDI_VERSION < NTDDI_VISTA
  119. #undef _PY_EMULATED_WIN_CV
  120. #define _PY_EMULATED_WIN_CV 1
  121. #endif
  122. #if _PY_EMULATED_WIN_CV
  123. /* The mutex is a CriticalSection object and
  124. The condition variables is emulated with the help of a semaphore.
  125. Semaphores are available on Windows XP (2003 server) and later.
  126. We use a Semaphore rather than an auto-reset event, because although
  127. an auto-resent event might appear to solve the lost-wakeup bug (race
  128. condition between releasing the outer lock and waiting) because it
  129. maintains state even though a wait hasn't happened, there is still
  130. a lost wakeup problem if more than one thread are interrupted in the
  131. critical place. A semaphore solves that, because its state is counted,
  132. not Boolean.
  133. Because it is ok to signal a condition variable with no one
  134. waiting, we need to keep track of the number of
  135. waiting threads. Otherwise, the semaphore's state could rise
  136. without bound. This also helps reduce the number of "spurious wakeups"
  137. that would otherwise happen.
  138. This implementation still has the problem that the threads woken
  139. with a "signal" aren't necessarily those that are already
  140. waiting. It corresponds to listing 2 in:
  141. http://birrell.org/andrew/papers/ImplementingCVs.pdf
  142. Generic emulations of the pthread_cond_* API using
  143. earlier Win32 functions can be found on the Web.
  144. The following read can be give background information to these issues,
  145. but the implementations are all broken in some way.
  146. http://www.cse.wustl.edu/~schmidt/win32-cv-1.html
  147. */
  148. typedef CRITICAL_SECTION PyMUTEX_T;
  149. Py_LOCAL_INLINE(int)
  150. PyMUTEX_INIT(PyMUTEX_T *cs)
  151. {
  152. InitializeCriticalSection(cs);
  153. return 0;
  154. }
  155. Py_LOCAL_INLINE(int)
  156. PyMUTEX_FINI(PyMUTEX_T *cs)
  157. {
  158. DeleteCriticalSection(cs);
  159. return 0;
  160. }
  161. Py_LOCAL_INLINE(int)
  162. PyMUTEX_LOCK(PyMUTEX_T *cs)
  163. {
  164. EnterCriticalSection(cs);
  165. return 0;
  166. }
  167. Py_LOCAL_INLINE(int)
  168. PyMUTEX_UNLOCK(PyMUTEX_T *cs)
  169. {
  170. LeaveCriticalSection(cs);
  171. return 0;
  172. }
  173. /* The ConditionVariable object. From XP onwards it is easily emulated with
  174. * a Semaphore
  175. */
  176. typedef struct _PyCOND_T
  177. {
  178. HANDLE sem;
  179. int waiting; /* to allow PyCOND_SIGNAL to be a no-op */
  180. } PyCOND_T;
  181. Py_LOCAL_INLINE(int)
  182. PyCOND_INIT(PyCOND_T *cv)
  183. {
  184. /* A semaphore with a "large" max value, The positive value
  185. * is only needed to catch those "lost wakeup" events and
  186. * race conditions when a timed wait elapses.
  187. */
  188. cv->sem = CreateSemaphore(NULL, 0, 100000, NULL);
  189. if (cv->sem==NULL)
  190. return -1;
  191. cv->waiting = 0;
  192. return 0;
  193. }
  194. Py_LOCAL_INLINE(int)
  195. PyCOND_FINI(PyCOND_T *cv)
  196. {
  197. return CloseHandle(cv->sem) ? 0 : -1;
  198. }
  199. /* this implementation can detect a timeout. Returns 1 on timeout,
  200. * 0 otherwise (and -1 on error)
  201. */
  202. Py_LOCAL_INLINE(int)
  203. _PyCOND_WAIT_MS(PyCOND_T *cv, PyMUTEX_T *cs, DWORD ms)
  204. {
  205. DWORD wait;
  206. cv->waiting++;
  207. PyMUTEX_UNLOCK(cs);
  208. /* "lost wakeup bug" would occur if the caller were interrupted here,
  209. * but we are safe because we are using a semaphore which has an internal
  210. * count.
  211. */
  212. wait = WaitForSingleObjectEx(cv->sem, ms, FALSE);
  213. PyMUTEX_LOCK(cs);
  214. if (wait != WAIT_OBJECT_0)
  215. --cv->waiting;
  216. /* Here we have a benign race condition with PyCOND_SIGNAL.
  217. * When failure occurs or timeout, it is possible that
  218. * PyCOND_SIGNAL also decrements this value
  219. * and signals releases the mutex. This is benign because it
  220. * just means an extra spurious wakeup for a waiting thread.
  221. * ('waiting' corresponds to the semaphore's "negative" count and
  222. * we may end up with e.g. (waiting == -1 && sem.count == 1). When
  223. * a new thread comes along, it will pass right throuhgh, having
  224. * adjusted it to (waiting == 0 && sem.count == 0).
  225. */
  226. if (wait == WAIT_FAILED)
  227. return -1;
  228. /* return 0 on success, 1 on timeout */
  229. return wait != WAIT_OBJECT_0;
  230. }
  231. Py_LOCAL_INLINE(int)
  232. PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs)
  233. {
  234. int result = _PyCOND_WAIT_MS(cv, cs, INFINITE);
  235. return result >= 0 ? 0 : result;
  236. }
  237. Py_LOCAL_INLINE(int)
  238. PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long long us)
  239. {
  240. return _PyCOND_WAIT_MS(cv, cs, (DWORD)(us/1000));
  241. }
  242. Py_LOCAL_INLINE(int)
  243. PyCOND_SIGNAL(PyCOND_T *cv)
  244. {
  245. /* this test allows PyCOND_SIGNAL to be a no-op unless required
  246. * to wake someone up, thus preventing an unbounded increase of
  247. * the semaphore's internal counter.
  248. */
  249. if (cv->waiting > 0) {
  250. /* notifying thread decreases the cv->waiting count so that
  251. * a delay between notify and actual wakeup of the target thread
  252. * doesn't cause a number of extra ReleaseSemaphore calls.
  253. */
  254. cv->waiting--;
  255. return ReleaseSemaphore(cv->sem, 1, NULL) ? 0 : -1;
  256. }
  257. return 0;
  258. }
  259. Py_LOCAL_INLINE(int)
  260. PyCOND_BROADCAST(PyCOND_T *cv)
  261. {
  262. int waiting = cv->waiting;
  263. if (waiting > 0) {
  264. cv->waiting = 0;
  265. return ReleaseSemaphore(cv->sem, waiting, NULL) ? 0 : -1;
  266. }
  267. return 0;
  268. }
  269. #else
  270. /* Use native Win7 primitives if build target is Win7 or higher */
  271. /* SRWLOCK is faster and better than CriticalSection */
  272. typedef SRWLOCK PyMUTEX_T;
  273. Py_LOCAL_INLINE(int)
  274. PyMUTEX_INIT(PyMUTEX_T *cs)
  275. {
  276. InitializeSRWLock(cs);
  277. return 0;
  278. }
  279. Py_LOCAL_INLINE(int)
  280. PyMUTEX_FINI(PyMUTEX_T *cs)
  281. {
  282. return 0;
  283. }
  284. Py_LOCAL_INLINE(int)
  285. PyMUTEX_LOCK(PyMUTEX_T *cs)
  286. {
  287. AcquireSRWLockExclusive(cs);
  288. return 0;
  289. }
  290. Py_LOCAL_INLINE(int)
  291. PyMUTEX_UNLOCK(PyMUTEX_T *cs)
  292. {
  293. ReleaseSRWLockExclusive(cs);
  294. return 0;
  295. }
  296. typedef CONDITION_VARIABLE PyCOND_T;
  297. Py_LOCAL_INLINE(int)
  298. PyCOND_INIT(PyCOND_T *cv)
  299. {
  300. InitializeConditionVariable(cv);
  301. return 0;
  302. }
  303. Py_LOCAL_INLINE(int)
  304. PyCOND_FINI(PyCOND_T *cv)
  305. {
  306. return 0;
  307. }
  308. Py_LOCAL_INLINE(int)
  309. PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs)
  310. {
  311. return SleepConditionVariableSRW(cv, cs, INFINITE, 0) ? 0 : -1;
  312. }
  313. /* This implementation makes no distinction about timeouts. Signal
  314. * 2 to indicate that we don't know.
  315. */
  316. Py_LOCAL_INLINE(int)
  317. PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long long us)
  318. {
  319. return SleepConditionVariableSRW(cv, cs, (DWORD)(us/1000), 0) ? 2 : -1;
  320. }
  321. Py_LOCAL_INLINE(int)
  322. PyCOND_SIGNAL(PyCOND_T *cv)
  323. {
  324. WakeConditionVariable(cv);
  325. return 0;
  326. }
  327. Py_LOCAL_INLINE(int)
  328. PyCOND_BROADCAST(PyCOND_T *cv)
  329. {
  330. WakeAllConditionVariable(cv);
  331. return 0;
  332. }
  333. #endif /* _PY_EMULATED_WIN_CV */
  334. #endif /* _POSIX_THREADS, NT_THREADS */
  335. #endif /* _CONDVAR_H_ */