-#if !defined(_MSC_VER)
- lock_grab(&WaitLock);
- if (threadID >= ActiveThreads)
- pthread_cond_wait(&WaitCond[threadID], &WaitLock);
- lock_release(&WaitLock);
-#else
- WaitForSingleObject(WaitCond[threadID], INFINITE);
-#endif
+ // Retest condition under lock protection
+ if (!( threadID >= ActiveThreads
+ || threads[threadID].state == THREAD_INITIALIZING
+ || (!sp && threads[threadID].state == THREAD_AVAILABLE)))
+ {
+ lock_release(&MPLock);
+ continue;
+ }
+
+ // Put thread to sleep
+ threads[threadID].state = THREAD_AVAILABLE;
+ cond_wait(&WaitCond[threadID], &MPLock);
+ lock_release(&MPLock);