From 6682f2c4155a1b606566cc6461a62da643aba6ef Mon Sep 17 00:00:00 2001 From: James Zern Date: Mon, 10 Jun 2019 20:58:30 -0700 Subject: [PATCH] thread_utils: release mutex before signaling holding the associated mutex while signaling a condition variable isn't necessary and in some implementations will reduce performance as the woken thread may test the mutex, fail and go back to sleep. Change-Id: Id685a47b0c76fc4a1c5acedcb6623e8c55056415 --- src/utils/thread_utils.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/utils/thread_utils.c b/src/utils/thread_utils.c index 2052b6b0..438296b4 100644 --- a/src/utils/thread_utils.c +++ b/src/utils/thread_utils.c @@ -217,8 +217,12 @@ static THREADFN ThreadLoop(void* ptr) { done = 1; } // signal to the main thread that we're done (for Sync()) - pthread_cond_signal(&impl->condition_); + // Note the associated mutex does not need to be held when signaling the + // condition. Unlocking the mutex first may improve performance in some + // implementations, avoiding the case where the waiting thread can't + // reacquire the mutex when woken. pthread_mutex_unlock(&impl->mutex_); + pthread_cond_signal(&impl->condition_); } return THREAD_RETURN(NULL); // Thread is finished } @@ -240,7 +244,13 @@ static void ChangeState(WebPWorker* const worker, WebPWorkerStatus new_status) { // assign new status and release the working thread if needed if (new_status != OK) { worker->status_ = new_status; + // Note the associated mutex does not need to be held when signaling the + // condition. Unlocking the mutex first may improve performance in some + // implementations, avoiding the case where the waiting thread can't + // reacquire the mutex when woken. + pthread_mutex_unlock(&impl->mutex_); pthread_cond_signal(&impl->condition_); + return; } } pthread_mutex_unlock(&impl->mutex_);