[2.7] bpo-30765: Avoid blocking when PyThread_acquire_lock() is asked… · python/cpython@8284883 (original) (raw)
`@@ -410,31 +410,41 @@ PyThread_free_lock(PyThread_type_lock lock)
`
410
410
`int
`
411
411
`PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
`
412
412
`{
`
413
``
`-
int success;
`
``
413
`+
int success = 0;
`
414
414
`pthread_lock *thelock = (pthread_lock *)lock;
`
415
415
`int status, error = 0;
`
416
416
``
417
417
`dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
`
418
418
``
419
``
`-
status = pthread_mutex_lock( &thelock->mut );
`
420
``
`-
CHECK_STATUS("pthread_mutex_lock[1]");
`
421
``
`-
success = thelock->locked == 0;
`
422
``
-
423
``
`-
if ( !success && waitflag ) {
`
424
``
`-
/* continue trying until we get the lock */
`
425
``
-
426
``
`-
/* mut must be locked by me -- part of the condition
`
427
``
`-
- protocol */
`
428
``
`-
while ( thelock->locked ) {
`
429
``
`-
status = pthread_cond_wait(&thelock->lock_released,
`
430
``
`-
&thelock->mut);
`
431
``
`-
CHECK_STATUS("pthread_cond_wait");
`
``
419
`+
if (waitflag) {
`
``
420
`+
status = pthread_mutex_lock( &thelock->mut );
`
``
421
`+
CHECK_STATUS("pthread_mutex_lock[1]");
`
``
422
`+
}
`
``
423
`+
else {
`
``
424
`+
status = pthread_mutex_trylock( &thelock->mut );
`
``
425
`+
if (status != EBUSY)
`
``
426
`+
CHECK_STATUS("pthread_mutex_trylock[1]");
`
``
427
`+
}
`
``
428
`+
if (status == 0) {
`
``
429
`+
success = thelock->locked == 0;
`
``
430
+
``
431
`+
if ( !success && waitflag ) {
`
``
432
`+
/* continue trying until we get the lock */
`
``
433
+
``
434
`+
/* mut must be locked by me -- part of the condition
`
``
435
`+
- protocol */
`
``
436
`+
while ( thelock->locked ) {
`
``
437
`+
status = pthread_cond_wait(&thelock->lock_released,
`
``
438
`+
&thelock->mut);
`
``
439
`+
CHECK_STATUS("pthread_cond_wait");
`
``
440
`+
}
`
``
441
`+
success = 1;
`
432
442
` }
`
433
``
`-
success = 1;
`
``
443
+
``
444
`+
if (success) thelock->locked = 1;
`
``
445
`+
status = pthread_mutex_unlock( &thelock->mut );
`
``
446
`+
CHECK_STATUS("pthread_mutex_unlock[1]");
`
434
447
` }
`
435
``
`-
if (success) thelock->locked = 1;
`
436
``
`-
status = pthread_mutex_unlock( &thelock->mut );
`
437
``
`-
CHECK_STATUS("pthread_mutex_unlock[1]");
`
438
448
``
439
449
`if (error) success = 0;
`
440
450
`dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
`