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.

270 lines
8.9 KiB

  1. /*
  2. * Implementation of the Global Interpreter Lock (GIL).
  3. */
  4. #include <stdlib.h>
  5. #include <errno.h>
  6. /* First some general settings */
  7. /* microseconds (the Python API uses seconds, though) */
  8. #define DEFAULT_INTERVAL 5000
  9. static unsigned long gil_interval = DEFAULT_INTERVAL;
  10. #define INTERVAL (gil_interval >= 1 ? gil_interval : 1)
  11. /* Enable if you want to force the switching of threads at least every `gil_interval` */
  12. #undef FORCE_SWITCHING
  13. #define FORCE_SWITCHING
  14. /*
  15. Notes about the implementation:
  16. - The GIL is just a boolean variable (gil_locked) whose access is protected
  17. by a mutex (gil_mutex), and whose changes are signalled by a condition
  18. variable (gil_cond). gil_mutex is taken for short periods of time,
  19. and therefore mostly uncontended.
  20. - In the GIL-holding thread, the main loop (PyEval_EvalFrameEx) must be
  21. able to release the GIL on demand by another thread. A volatile boolean
  22. variable (gil_drop_request) is used for that purpose, which is checked
  23. at every turn of the eval loop. That variable is set after a wait of
  24. `interval` microseconds on `gil_cond` has timed out.
  25. [Actually, another volatile boolean variable (eval_breaker) is used
  26. which ORs several conditions into one. Volatile booleans are
  27. sufficient as inter-thread signalling means since Python is run
  28. on cache-coherent architectures only.]
  29. - A thread wanting to take the GIL will first let pass a given amount of
  30. time (`interval` microseconds) before setting gil_drop_request. This
  31. encourages a defined switching period, but doesn't enforce it since
  32. opcodes can take an arbitrary time to execute.
  33. The `interval` value is available for the user to read and modify
  34. using the Python API `sys.{get,set}switchinterval()`.
  35. - When a thread releases the GIL and gil_drop_request is set, that thread
  36. ensures that another GIL-awaiting thread gets scheduled.
  37. It does so by waiting on a condition variable (switch_cond) until
  38. the value of gil_last_holder is changed to something else than its
  39. own thread state pointer, indicating that another thread was able to
  40. take the GIL.
  41. This is meant to prohibit the latency-adverse behaviour on multi-core
  42. machines where one thread would speculatively release the GIL, but still
  43. run and end up being the first to re-acquire it, making the "timeslices"
  44. much longer than expected.
  45. (Note: this mechanism is enabled with FORCE_SWITCHING above)
  46. */
  47. #include "condvar.h"
  48. #ifndef Py_HAVE_CONDVAR
  49. #error You need either a POSIX-compatible or a Windows system!
  50. #endif
  51. #define MUTEX_T PyMUTEX_T
  52. #define MUTEX_INIT(mut) \
  53. if (PyMUTEX_INIT(&(mut))) { \
  54. Py_FatalError("PyMUTEX_INIT(" #mut ") failed"); };
  55. #define MUTEX_FINI(mut) \
  56. if (PyMUTEX_FINI(&(mut))) { \
  57. Py_FatalError("PyMUTEX_FINI(" #mut ") failed"); };
  58. #define MUTEX_LOCK(mut) \
  59. if (PyMUTEX_LOCK(&(mut))) { \
  60. Py_FatalError("PyMUTEX_LOCK(" #mut ") failed"); };
  61. #define MUTEX_UNLOCK(mut) \
  62. if (PyMUTEX_UNLOCK(&(mut))) { \
  63. Py_FatalError("PyMUTEX_UNLOCK(" #mut ") failed"); };
  64. #define COND_T PyCOND_T
  65. #define COND_INIT(cond) \
  66. if (PyCOND_INIT(&(cond))) { \
  67. Py_FatalError("PyCOND_INIT(" #cond ") failed"); };
  68. #define COND_FINI(cond) \
  69. if (PyCOND_FINI(&(cond))) { \
  70. Py_FatalError("PyCOND_FINI(" #cond ") failed"); };
  71. #define COND_SIGNAL(cond) \
  72. if (PyCOND_SIGNAL(&(cond))) { \
  73. Py_FatalError("PyCOND_SIGNAL(" #cond ") failed"); };
  74. #define COND_WAIT(cond, mut) \
  75. if (PyCOND_WAIT(&(cond), &(mut))) { \
  76. Py_FatalError("PyCOND_WAIT(" #cond ") failed"); };
  77. #define COND_TIMED_WAIT(cond, mut, microseconds, timeout_result) \
  78. { \
  79. int r = PyCOND_TIMEDWAIT(&(cond), &(mut), (microseconds)); \
  80. if (r < 0) \
  81. Py_FatalError("PyCOND_WAIT(" #cond ") failed"); \
  82. if (r) /* 1 == timeout, 2 == impl. can't say, so assume timeout */ \
  83. timeout_result = 1; \
  84. else \
  85. timeout_result = 0; \
  86. } \
  87. /* Whether the GIL is already taken (-1 if uninitialized). This is atomic
  88. because it can be read without any lock taken in ceval.c. */
  89. static _Py_atomic_int gil_locked = {-1};
  90. /* Number of GIL switches since the beginning. */
  91. static unsigned long gil_switch_number = 0;
  92. /* Last PyThreadState holding / having held the GIL. This helps us know
  93. whether anyone else was scheduled after we dropped the GIL. */
  94. static _Py_atomic_address gil_last_holder = {NULL};
  95. /* This condition variable allows one or several threads to wait until
  96. the GIL is released. In addition, the mutex also protects the above
  97. variables. */
  98. static COND_T gil_cond;
  99. static MUTEX_T gil_mutex;
  100. #ifdef FORCE_SWITCHING
  101. /* This condition variable helps the GIL-releasing thread wait for
  102. a GIL-awaiting thread to be scheduled and take the GIL. */
  103. static COND_T switch_cond;
  104. static MUTEX_T switch_mutex;
  105. #endif
  106. static int gil_created(void)
  107. {
  108. return _Py_atomic_load_explicit(&gil_locked, _Py_memory_order_acquire) >= 0;
  109. }
  110. static void create_gil(void)
  111. {
  112. MUTEX_INIT(gil_mutex);
  113. #ifdef FORCE_SWITCHING
  114. MUTEX_INIT(switch_mutex);
  115. #endif
  116. COND_INIT(gil_cond);
  117. #ifdef FORCE_SWITCHING
  118. COND_INIT(switch_cond);
  119. #endif
  120. _Py_atomic_store_relaxed(&gil_last_holder, NULL);
  121. _Py_ANNOTATE_RWLOCK_CREATE(&gil_locked);
  122. _Py_atomic_store_explicit(&gil_locked, 0, _Py_memory_order_release);
  123. }
  124. static void destroy_gil(void)
  125. {
  126. /* some pthread-like implementations tie the mutex to the cond
  127. * and must have the cond destroyed first.
  128. */
  129. COND_FINI(gil_cond);
  130. MUTEX_FINI(gil_mutex);
  131. #ifdef FORCE_SWITCHING
  132. COND_FINI(switch_cond);
  133. MUTEX_FINI(switch_mutex);
  134. #endif
  135. _Py_atomic_store_explicit(&gil_locked, -1, _Py_memory_order_release);
  136. _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked);
  137. }
  138. static void recreate_gil(void)
  139. {
  140. _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked);
  141. /* XXX should we destroy the old OS resources here? */
  142. create_gil();
  143. }
  144. static void drop_gil(PyThreadState *tstate)
  145. {
  146. if (!_Py_atomic_load_relaxed(&gil_locked))
  147. Py_FatalError("drop_gil: GIL is not locked");
  148. /* tstate is allowed to be NULL (early interpreter init) */
  149. if (tstate != NULL) {
  150. /* Sub-interpreter support: threads might have been switched
  151. under our feet using PyThreadState_Swap(). Fix the GIL last
  152. holder variable so that our heuristics work. */
  153. _Py_atomic_store_relaxed(&gil_last_holder, tstate);
  154. }
  155. MUTEX_LOCK(gil_mutex);
  156. _Py_ANNOTATE_RWLOCK_RELEASED(&gil_locked, /*is_write=*/1);
  157. _Py_atomic_store_relaxed(&gil_locked, 0);
  158. COND_SIGNAL(gil_cond);
  159. MUTEX_UNLOCK(gil_mutex);
  160. #ifdef FORCE_SWITCHING
  161. if (_Py_atomic_load_relaxed(&gil_drop_request) && tstate != NULL) {
  162. MUTEX_LOCK(switch_mutex);
  163. /* Not switched yet => wait */
  164. if (_Py_atomic_load_relaxed(&gil_last_holder) == tstate) {
  165. RESET_GIL_DROP_REQUEST();
  166. /* NOTE: if COND_WAIT does not atomically start waiting when
  167. releasing the mutex, another thread can run through, take
  168. the GIL and drop it again, and reset the condition
  169. before we even had a chance to wait for it. */
  170. COND_WAIT(switch_cond, switch_mutex);
  171. }
  172. MUTEX_UNLOCK(switch_mutex);
  173. }
  174. #endif
  175. }
  176. static void take_gil(PyThreadState *tstate)
  177. {
  178. int err;
  179. if (tstate == NULL)
  180. Py_FatalError("take_gil: NULL tstate");
  181. err = errno;
  182. MUTEX_LOCK(gil_mutex);
  183. if (!_Py_atomic_load_relaxed(&gil_locked))
  184. goto _ready;
  185. while (_Py_atomic_load_relaxed(&gil_locked)) {
  186. int timed_out = 0;
  187. unsigned long saved_switchnum;
  188. saved_switchnum = gil_switch_number;
  189. COND_TIMED_WAIT(gil_cond, gil_mutex, INTERVAL, timed_out);
  190. /* If we timed out and no switch occurred in the meantime, it is time
  191. to ask the GIL-holding thread to drop it. */
  192. if (timed_out &&
  193. _Py_atomic_load_relaxed(&gil_locked) &&
  194. gil_switch_number == saved_switchnum) {
  195. SET_GIL_DROP_REQUEST();
  196. }
  197. }
  198. _ready:
  199. #ifdef FORCE_SWITCHING
  200. /* This mutex must be taken before modifying gil_last_holder (see drop_gil()). */
  201. MUTEX_LOCK(switch_mutex);
  202. #endif
  203. /* We now hold the GIL */
  204. _Py_atomic_store_relaxed(&gil_locked, 1);
  205. _Py_ANNOTATE_RWLOCK_ACQUIRED(&gil_locked, /*is_write=*/1);
  206. if (tstate != _Py_atomic_load_relaxed(&gil_last_holder)) {
  207. _Py_atomic_store_relaxed(&gil_last_holder, tstate);
  208. ++gil_switch_number;
  209. }
  210. #ifdef FORCE_SWITCHING
  211. COND_SIGNAL(switch_cond);
  212. MUTEX_UNLOCK(switch_mutex);
  213. #endif
  214. if (_Py_atomic_load_relaxed(&gil_drop_request)) {
  215. RESET_GIL_DROP_REQUEST();
  216. }
  217. if (tstate->async_exc != NULL) {
  218. _PyEval_SignalAsyncExc();
  219. }
  220. MUTEX_UNLOCK(gil_mutex);
  221. errno = err;
  222. }
  223. void _PyEval_SetSwitchInterval(unsigned long microseconds)
  224. {
  225. gil_interval = microseconds;
  226. }
  227. unsigned long _PyEval_GetSwitchInterval()
  228. {
  229. return gil_interval;
  230. }