@@ -91,8 +91,8 @@ _PySemaphore_Destroy(_PySemaphore *sema)
9191#endif
9292}
9393
94- int
95- _PySemaphore_Wait (_PySemaphore * sema , PyTime_t timeout )
94+ static int
95+ _PySemaphore_PlatformWait (_PySemaphore * sema , PyTime_t timeout )
9696{
9797 int res ;
9898#if defined(MS_WINDOWS )
@@ -225,6 +225,27 @@ _PySemaphore_Wait(_PySemaphore *sema, PyTime_t timeout)
225225 return res ;
226226}
227227
228+ int
229+ _PySemaphore_Wait (_PySemaphore * sema , PyTime_t timeout , int detach )
230+ {
231+ PyThreadState * tstate = NULL ;
232+ if (detach ) {
233+ tstate = _PyThreadState_GET ();
234+ if (tstate && _PyThreadState_IsAttached (tstate )) {
235+ // Only detach if we are attached
236+ PyEval_ReleaseThread (tstate );
237+ }
238+ else {
239+ tstate = NULL ;
240+ }
241+ }
242+ int res = _PySemaphore_PlatformWait (sema , timeout );
243+ if (tstate ) {
244+ PyEval_AcquireThread (tstate );
245+ }
246+ return res ;
247+ }
248+
228249void
229250_PySemaphore_Wakeup (_PySemaphore * sema )
230251{
@@ -333,7 +354,7 @@ _PyParkingLot_Park(const void *addr, const void *expected, size_t size,
333354 }
334355 }
335356
336- int res = _PySemaphore_Wait (& wait .sema , timeout_ns );
357+ int res = _PySemaphore_Wait (& wait .sema , timeout_ns , 0 );
337358 if (res == Py_PARK_OK ) {
338359 goto done ;
339360 }
@@ -345,7 +366,7 @@ _PyParkingLot_Park(const void *addr, const void *expected, size_t size,
345366 // Another thread has started to unpark us. Wait until we process the
346367 // wakeup signal.
347368 do {
348- res = _PySemaphore_Wait (& wait .sema , -1 );
369+ res = _PySemaphore_Wait (& wait .sema , -1 , 0 );
349370 } while (res != Py_PARK_OK );
350371 goto done ;
351372 }
0 commit comments