- // Do sleep here after retesting sleep conditions
- if (threadID >= activeThreads || threads[threadID].state == Thread::AVAILABLE)
- cond_wait(&threads[threadID].sleepCond, &threads[threadID].sleepLock);
+ // Do sleep after retesting sleep conditions under lock protection, in
+ // particular we need to avoid a deadlock in case a master thread has,
+ // in the meanwhile, allocated us and sent the wake_up() call before we
+ // had the chance to grab the lock.
+ if (do_sleep || state == Thread::AVAILABLE)
+ cond_wait(&sleepCond, &sleepLock);