| 1 | |
| 2 | /* Idea: |
| 3 | |
| 4 | 0. "The GIL" is a composite concept. There are two locks, and "the |
| 5 | GIL is locked" when both are locked. |
| 6 | |
| 7 | 1. The first lock is a simple global variable 'rpy_fastgil'. 0 means |
| 8 | unlocked, != 0 means unlocked (see point (3). |
| 9 | |
| 10 | 2. The second lock is a regular mutex called 'mutex_gil'. In the fast path, |
| 11 | it is never unlocked. Remember that "the GIL is unlocked" means that |
| 12 | either the first or the second lock is unlocked. It should never be the |
| 13 | case that both are unlocked at the same time. |
| 14 | |
| 15 | 3. Whenever the GIL is locked, rpy_fastgil contains the thread ID of the |
| 16 | thread holding the GIL. Note that there is a period of time in which |
| 17 | rpy_fastgil contains a thread ID, but the GIL itself is not locked |
| 18 | because the mutex in point (2) is unlocked: however, this happens only |
| 19 | inside the functions RPyGilAcquireSlowPath and RPyGilYieldThread. So, for |
| 20 | "general" code, you can easily check whether you are holding the GIL by |
| 21 | doing: rpy_fastgil == rthread.get_ident() |
| 22 | |
| 23 | With this setup, we have a very fast way to release/acquire the GIL: |
| 24 | |
| 25 | 4. To release, you set rpy_fastgil=0; the invariant is that mutex_gil is |
| 26 | still locked at this point. |
| 27 | |
| 28 | 5. To acquire, you do a compare_and_swap on rpy_fastgil: if it was 0, then |
| 29 | it means the mutex_gil was already locked, so you have the GIL and you |
| 30 | are done. If rpy_fastgil was NOT 0, the compare_and_swap fails, so you |
| 31 | must go through the slow path in RPyGilAcquireSlowPath |
| 32 | |
| 33 | This fast path is implemented in two places: |
| 34 | |
| 35 | * RPyGilAcquire, to be called by general RPython code |
| 36 | |
| 37 | * By native code emitted by the JIT around external calls; look e.g. to |
| 38 | rpython.jit.backend.x86.callbuilder:move_real_result_and_call_reacqgil_addr |
| 39 | |
| 40 | |
| 41 | The slow path works as follows: |
| 42 | |
| 43 | 6. Suppose there are many threads which want the GIL: at any point in time, |
| 44 | only one will actively try to acquire the GIL. This is called "the |
| 45 | stealer". |
| 46 | |
| 47 | 7. To become the stealer, you need to acquire 'mutex_gil_stealer'. |
| 48 | |
| 49 | 8. Once you are the stealer, you try to acquire the GIL by running the |
| 50 | following loop: |
| 51 | |
| 52 | A. We try again to lock the GIL using the fast-path. |
| 53 | |
| 54 | B. Try to acquire 'mutex_gil' with a timeout. If you succeed, you set |
| 55 | rpy_fastgil and you are done. If not, go to A. |
| 56 | |
| 57 | |
| 58 | |
| 59 | To sum up, there are various possible patterns of interaction: |
| 60 | |
| 61 | - I release the GIL using the fast-path: the GIL will be acquired by a |
| 62 | thread in the fast path in point (2) OR the fast path in point (8.A). Note |
| 63 | that this could be myself a bit later |
| 64 | |
| 65 | - I want to explicitly yield the control to ANOTHER thread: I do this by |
| 66 | releasing mutex_gil: the stealer will acquire the GIL in point (8.B). |
| 67 | |
| 68 | - I want the GIL and there are exactly 2 threads in total: I will |
| 69 | immediately become the stealer and go to point 8 |
| 70 | |
| 71 | - I want the GIL but there are more than 2 threads in total: I will spend |
| 72 | most of my time waiting for mutex_gil_stealer, and then go to point 8 |
| 73 | |
| 74 | |
| 75 | */ |
| 76 | |
| 77 | |
| 78 | /* The GIL is initially released; see pypy_main_function(), which calls |
| 79 | RPyGilAcquire/RPyGilRelease. The point is that when building |
| 80 | RPython libraries, they can be a collection of regular functions that |
| 81 | also call RPyGilAcquire/RPyGilRelease; see test_standalone.TestShared. |
| 82 | */ |
| 83 | |
| 84 | #include "src/threadlocal.h" |
| 85 | |
| 86 | Signed rpy_fastgil = 0; |
| 87 | static Signed rpy_waiting_threads = -42; /* GIL not initialized */ |
| 88 | static volatile int rpy_early_poll_n = 0; |
| 89 | static mutex1_t mutex_gil_stealer; |
| 90 | static mutex2_t mutex_gil; |
| 91 | |
| 92 | |
| 93 | static void rpy_init_mutexes(void) |
| 94 | { |
| 95 | mutex1_init(&mutex_gil_stealer); |
| 96 | mutex2_init_locked(&mutex_gil); |
| 97 | rpy_waiting_threads = 0; |
| 98 | } |
| 99 | |
| 100 | void RPyGilAllocate(void) |
| 101 | { |
| 102 | if (rpy_waiting_threads < 0) { |
| 103 | assert(rpy_waiting_threads == -42); |
| 104 | rpy_init_mutexes(); |
| 105 | #ifdef HAVE_PTHREAD_ATFORK |
| 106 | pthread_atfork(NULL, NULL, rpy_init_mutexes); |
| 107 | #endif |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | #define RPY_GIL_POKE_MIN 40 |
| 112 | #define RPY_GIL_POKE_MAX 400 |
| 113 | |
| 114 | void RPyGilAcquireSlowPath(void) |
| 115 | { |
| 116 | /* Acquires the GIL. This is the slow path after which we failed |
| 117 | the compare-and-swap (after point (5)). Another thread is busy |
| 118 | with the GIL. |
| 119 | */ |
| 120 | if (1) { /* preserve commit history */ |
| 121 | int n; |
| 122 | Signed old_waiting_threads; |
| 123 | |
| 124 | if (rpy_waiting_threads < 0) { |
| 125 | /* <arigo> I tried to have RPyGilAllocate() called from |
| 126 | * here, but it fails occasionally on an example |
| 127 | * (2.7/test/test_threading.py). I think what occurs is |
| 128 | * that if one thread runs RPyGilAllocate(), it still |
| 129 | * doesn't have the GIL; then the other thread might fork() |
| 130 | * at precisely this moment, killing the first thread. |
| 131 | */ |
| 132 | fprintf(stderr, "Fatal RPython error: a thread is trying to wait " |
| 133 | "for the GIL, but the GIL was not initialized\n" |
| 134 | "(For PyPy, see " |
| 135 | "https://foss.heptapod.net/pypy/pypy/-/issues/2274)\n"); |
| 136 | abort(); |
| 137 | } |
| 138 | |
| 139 | /* Register me as one of the threads that is actively waiting |
| 140 | for the GIL. The number of such threads is found in |
| 141 | rpy_waiting_threads. */ |
| 142 | old_waiting_threads = atomic_increment(&rpy_waiting_threads); |
| 143 | |
| 144 | /* Early polling: before entering the waiting queue, we check |
| 145 | a certain number of times if the GIL becomes free. The |
| 146 | motivation for this is issue #2341. Note that we do this |
| 147 | polling even if there are already other threads in the |
| 148 | queue, and one of thesee threads is the stealer. This is |
| 149 | because the stealer is likely sleeping right now. There |
| 150 | are use cases where the GIL will really be released very |
| 151 | soon after RPyGilAcquireSlowPath() is called, so it's worth |
| 152 | always doing this check. |
| 153 | |
| 154 | To avoid falling into bad cases, we "randomize" the number |
| 155 | of iterations: we loop N times, where N is choosen between |
| 156 | RPY_GIL_POKE_MIN and RPY_GIL_POKE_MAX. |
| 157 | */ |
| 158 | n = rpy_early_poll_n * 2 + 1; |
| 159 | while (n >= RPY_GIL_POKE_MAX) |
| 160 | n -= (RPY_GIL_POKE_MAX - RPY_GIL_POKE_MIN); |
| 161 | rpy_early_poll_n = n; |
| 162 | while (n >= 0) { |
| 163 | n--; |
| 164 | if (old_waiting_threads != rpy_waiting_threads) { |
| 165 | /* If the number changed, it is because another thread |
| 166 | entered or left this function. In that case, stop |
| 167 | this loop: if another thread left it means the GIL |
| 168 | has been acquired by that thread; if another thread |
| 169 | entered there is no point in running the present |
| 170 | loop twice. */ |
| 171 | break; |
| 172 | } |
| 173 | RPy_YieldProcessor(); |
| 174 | RPy_CompilerMemoryBarrier(); |
| 175 | |
| 176 | if (!RPY_FASTGIL_LOCKED(rpy_fastgil)) { |
| 177 | if (_rpygil_acquire_fast_path()) { |
| 178 | /* We got the gil before entering the waiting |
| 179 | queue. In case there are other threads waiting |
| 180 | for the GIL, wake up the stealer thread now and |
| 181 | go to the waiting queue anyway, for fairness. |
| 182 | This will fall through if there are no other |
| 183 | threads waiting. |
| 184 | */ |
| 185 | assert(RPY_FASTGIL_LOCKED(rpy_fastgil)); |
| 186 | mutex2_unlock(&mutex_gil); |
| 187 | break; |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /* Now we are in point (3): mutex_gil might be released, but |
| 193 | rpy_fastgil might still contain an arbitrary tid */ |
| 194 | |
| 195 | /* Enter the waiting queue from the end. Assuming a roughly |
| 196 | first-in-first-out order, this will nicely give the threads |
| 197 | a round-robin chance. |
| 198 | */ |
| 199 | mutex1_lock(&mutex_gil_stealer); |
| 200 | mutex2_loop_start(&mutex_gil); |
| 201 | |
| 202 | /* We are now the stealer thread. Steals! */ |
| 203 | while (1) { |
| 204 | /* Busy-looping here. Try to look again if 'rpy_fastgil' is |
| 205 | released. |
| 206 | */ |
| 207 | if (!RPY_FASTGIL_LOCKED(rpy_fastgil)) { |
| 208 | /* point (8.A) */ |
| 209 | if (_rpygil_acquire_fast_path()) { |
| 210 | /* we just acquired the GIL */ |
| 211 | break; |
| 212 | } |
| 213 | } |
| 214 | /* Sleep for one interval of time. We may be woken up earlier |
| 215 | if 'mutex_gil' is released. Point (8.B) |
| 216 | */ |
| 217 | if (mutex2_lock_timeout(&mutex_gil, 0.0001)) { /* 0.1 ms... */ |
| 218 | /* We arrive here if 'mutex_gil' was recently released |
| 219 | and we just relocked it. |
| 220 | */ |
| 221 | assert(RPY_FASTGIL_LOCKED(rpy_fastgil)); |
| 222 | /* restore the invariant point (3) */ |
| 223 | rpy_fastgil = _rpygil_get_my_ident(); |
| 224 | break; |
| 225 | } |
| 226 | /* Loop back. */ |
| 227 | } |
| 228 | atomic_decrement(&rpy_waiting_threads); |
| 229 | mutex2_loop_stop(&mutex_gil); |
| 230 | mutex1_unlock(&mutex_gil_stealer); |
| 231 | } |
| 232 | assert(RPY_FASTGIL_LOCKED(rpy_fastgil)); |
| 233 | } |
| 234 | |
| 235 | Signed RPyGilYieldThread(void) |
| 236 | { |
| 237 | /* can be called even before RPyGilAllocate(), but in this case, |
| 238 | 'rpy_waiting_threads' will be -42. */ |
| 239 | assert(RPY_FASTGIL_LOCKED(rpy_fastgil)); |
| 240 | if (rpy_waiting_threads <= 0) |
| 241 | return 0; |
| 242 | |
| 243 | /* Explicitly release the 'mutex_gil'. |
| 244 | */ |
| 245 | mutex2_unlock(&mutex_gil); |
| 246 | |
| 247 | /* Now nobody has got the GIL, because 'mutex_gil' is released (but |
| 248 | rpy_fastgil is still locked). Call RPyGilAcquire(). It will |
| 249 | enqueue ourselves at the end of the 'mutex_gil_stealer' queue. |
| 250 | If there is no other waiting thread, it will fall through both |
| 251 | its mutex_lock() and mutex_lock_timeout() now. But that's |
| 252 | unlikely, because we tested above that 'rpy_waiting_threads > 0'. |
| 253 | */ |
| 254 | RPyGilAcquire(); |
| 255 | return 1; |
| 256 | } |
| 257 | |
| 258 | void RPyGilReleaseSignal(void) |
| 259 | { |
| 260 | #ifdef _WIN32 |
| 261 | /* Called after the fast-path GIL release (rpy_fastgil set to 0) to wake |
| 262 | any stealer thread that is sleeping in mutex2_lock_timeout(). Without |
| 263 | this, the stealer must wait for its timed-wait to expire, which on |
| 264 | Windows with the default 10-15 ms timer resolution causes severe |
| 265 | latency for any code that releases the GIL (e.g. os.stat, lock.acquire). |
| 266 | A missed wakeup (due to the signal arriving before the stealer enters its |
| 267 | timed-wait) is benign: the stealer will still wake up on its timeout and |
| 268 | then immediately acquire the GIL via the fast path. |
| 269 | On POSIX, the 0.1ms timeout in mutex2_lock_timeout() is short enough |
| 270 | that the extra wakeup is not needed and causes test_interrupt_non_main |
| 271 | to hang due to scheduling interference. */ |
| 272 | if (rpy_waiting_threads > 0) { |
| 273 | mutex2_signal(&mutex_gil); |
| 274 | } |
| 275 | #endif |
| 276 | } |
| 277 | |
| 278 | /********** for tests only **********/ |
| 279 | |
| 280 | /* These functions are usually defined as a macros RPyXyz() in thread.h |
| 281 | which get translated into calls to _RpyXyz(). But for tests we need |
| 282 | the real functions to exists in the library as well. |
| 283 | */ |
| 284 | |
| 285 | #undef RPyGilRelease |
| 286 | RPY_EXTERN |
| 287 | void RPyGilRelease(void) |
| 288 | { |
| 289 | /* Releases the GIL in order to do an external function call. |
| 290 | We assume that the common case is that the function call is |
| 291 | actually very short, and optimize accordingly. |
| 292 | */ |
| 293 | _RPyGilRelease(); |
| 294 | } |
| 295 | |
| 296 | #undef RPyGilAcquire |
| 297 | RPY_EXTERN |
| 298 | void RPyGilAcquire(void) |
| 299 | { |
| 300 | _RPyGilAcquire(); |
| 301 | } |
| 302 | |
| 303 | #undef RPyFetchFastGil |
| 304 | RPY_EXTERN |
| 305 | Signed *RPyFetchFastGil(void) |
| 306 | { |
| 307 | return _RPyFetchFastGil(); |
| 308 | } |
| 309 | |
| 310 | #undef RPyGilGetHolder |
| 311 | RPY_EXTERN |
| 312 | Signed RPyGilGetHolder(void) |
| 313 | { |
| 314 | return _RPyGilGetHolder(); |
| 315 | } |