- // Retest condition under lock protection
- if (!( threadID >= ActiveThreads
- || threads[threadID].state == THREAD_INITIALIZING
- || (!sp && threads[threadID].state == THREAD_AVAILABLE)))
+ // Test with lock held to avoid races with wake_sleeping_thread()
+ for (i = 0; sp && i < ActiveThreads && !sp->slaves[i]; i++) {}
+ allFinished = (i == ActiveThreads);
+
+ // Retest sleep conditions under lock protection
+ if ( AllThreadsShouldExit
+ || allFinished
+ || !( threadID >= ActiveThreads
+ || threads[threadID].state == THREAD_INITIALIZING
+ || (threads[threadID].state == THREAD_AVAILABLE && (!sp || UseSleepingMaster))))