thread_loop: lock/unlock mutex outside thread loop
It is not necessary to release and reacquire worker->impl_->mutex_
between iterations of the thread loop. We can acquire
worker->impl_->mutex_ before entering the thread loop and release
worker->impl_->mutex_ after exiting the thread loop.
Once we do this, we can exit the thread loop with a break statement and
get rid of the `done` boolean flag.
Finally, since worker->status_ has only three possible values, if it is
not OK and WORK, then it must be NOT_OK. So we can replace the last
else-if with an else. Also, if worker->status_ is assigned an invalid
value, the original code will enter an infinite loop. The else branch in
the new code will treat the invalid status as NOT_OK and exit the thread
loop.
Change-Id: I34f0bad43fe4f74dfc03813b59f64cc97b4cb6b9
diff --git a/aom_util/aom_thread.c b/aom_util/aom_thread.c
index 04a0bd6..2c62b24 100644
--- a/aom_util/aom_thread.c
+++ b/aom_util/aom_thread.c
@@ -62,9 +62,8 @@
pthread_setname_np(pthread_self(), thread_name);
}
#endif
- int done = 0;
- while (!done) {
- pthread_mutex_lock(&worker->impl_->mutex_);
+ pthread_mutex_lock(&worker->impl_->mutex_);
+ for (;;) {
while (worker->status_ == OK) { // wait in idling mode
pthread_cond_wait(&worker->impl_->condition_, &worker->impl_->mutex_);
}
@@ -81,11 +80,12 @@
worker->status_ = OK;
// signal to the main thread that we're done (for sync())
pthread_cond_signal(&worker->impl_->condition_);
- } else if (worker->status_ == NOT_OK) { // finish the worker
- done = 1;
+ } else {
+ assert(worker->status_ == NOT_OK); // finish the worker
+ break;
}
- pthread_mutex_unlock(&worker->impl_->mutex_);
}
+ pthread_mutex_unlock(&worker->impl_->mutex_);
return THREAD_RETURN(NULL); // Thread is finished
}