- // If we are not searching, wait for a condition to be signaled instead of
- // wasting CPU time polling for work.
- while ((!searching && Threads.sleepWhileIdle) || exit)
- {
- if (exit)
- {
- assert(!this_sp);
- return;
- }
-
- // Grab the lock to avoid races with Thread::notify_one()
- mutex.lock();
-
- // If we are master and all slaves have finished then exit idle_loop
- if (this_sp && this_sp->slavesMask.none())
- {
- mutex.unlock();
- break;
- }
-
- // 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 notify_one() call before
- // we had the chance to grab the lock.
- if (!searching && !exit)
- sleepCondition.wait(mutex);
-
- mutex.unlock();
- }
-
- // If this thread has been assigned work, launch a search
- if (searching)
- {
- assert(!exit);
-
- Threads.mutex.lock();
-
- assert(searching);
- assert(activeSplitPoint);
- SplitPoint* sp = activeSplitPoint;
-
- Threads.mutex.unlock();
-
- Stack stack[MAX_PLY_PLUS_6], *ss = stack+2; // To allow referencing (ss-2)
- Position pos(*sp->pos, this);
-
- std::memcpy(ss-2, sp->ss-2, 5 * sizeof(Stack));
- ss->splitPoint = sp;
-
- sp->mutex.lock();
-
- assert(activePosition == NULL);
-
- activePosition = &pos;
-
- switch (sp->nodeType) {
- case Root:
- search<SplitPointRoot>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
- break;
- case PV:
- search<SplitPointPV>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
- break;
- case NonPV:
- search<SplitPointNonPV>(pos, ss, sp->alpha, sp->beta, sp->depth, sp->cutNode);
- break;
- default:
- assert(false);
- }
-
- assert(searching);
-
- searching = false;
- activePosition = NULL;
- sp->slavesMask.reset(idx);
- sp->nodes += pos.nodes_searched();
-
- // Wake up the master thread so to allow it to return from the idle
- // loop in case we are the last slave of the split point.
- if ( Threads.sleepWhileIdle
- && this != sp->masterThread
- && sp->slavesMask.none())
- {
- assert(!sp->masterThread->searching);
- sp->masterThread->notify_one();
- }
-
- // After releasing the lock we can't access any SplitPoint related data
- // in a safe way because it could have been released under our feet by
- // the sp master. Also accessing other Thread objects is unsafe because
- // if we are exiting there is a chance that they are already freed.
- sp->mutex.unlock();
- }