LibPthread: Don't hold sem->mtx after sem_wait()/sem_trywait()

Semaphores with values greater than one didn't work because whoever
called sem_wait() first held the semaphore's mutex until a matching
sem_post() call.

Other callers then wouldn't be able to acquire the semaphore even
if the semaphore's value was still greater than zero at that point.
This commit is contained in:
Gunnar Beutner 2021-04-14 22:52:33 +02:00 committed by Andreas Kling
parent 32794e00a1
commit a44ddc4793
Notes: sideshowbarker 2024-07-18 20:19:35 +09:00

View File

@ -93,6 +93,12 @@ sem_t* sem_open(const char*, int, ...)
int sem_post(sem_t* sem)
{
auto rc = pthread_mutex_lock(&sem->mtx);
if (rc != 0) {
errno = rc;
return -1;
}
if (sem->value == SEM_VALUE_MAX) {
pthread_mutex_unlock(&sem->mtx);
errno = EOVERFLOW;
@ -101,7 +107,7 @@ int sem_post(sem_t* sem)
sem->value++;
auto rc = pthread_cond_signal(&sem->cv);
rc = pthread_cond_signal(&sem->cv);
if (rc != 0) {
pthread_mutex_unlock(&sem->mtx);
errno = rc;
@ -133,6 +139,12 @@ int sem_trywait(sem_t* sem)
sem->value--;
rc = pthread_mutex_unlock(&sem->mtx);
if (rc != 0) {
errno = rc;
return -1;
}
return 0;
}
@ -161,5 +173,11 @@ int sem_wait(sem_t* sem)
sem->value--;
rc = pthread_mutex_unlock(&sem->mtx);
if (rc != 0) {
errno = rc;
return -1;
}
return 0;
}