+// Thread::timer_loop() is where the timer thread waits maxPly milliseconds and
+// then calls check_time(). If maxPly is 0 thread sleeps until is woken up.
+extern void check_time();
+
+void Thread::timer_loop() {
+
+ while (!do_exit)
+ {
+ mutex.lock();
+ sleepCondition.wait_for(mutex, maxPly ? maxPly : INT_MAX);
+ mutex.unlock();
+ check_time();
+ }
+}
+
+
+// Thread::main_loop() is where the main thread is parked waiting to be started
+// when there is a new search. Main thread will launch all the slave threads.
+
+void Thread::main_loop() {
+
+ while (true)
+ {
+ mutex.lock();
+
+ do_sleep = true; // Always return to sleep after a search
+ is_searching = false;
+
+ while (do_sleep && !do_exit)
+ {
+ Threads.sleepCondition.notify_one(); // Wake up UI thread if needed
+ sleepCondition.wait(mutex);
+ }
+
+ mutex.unlock();
+
+ if (do_exit)
+ return;
+
+ is_searching = true;
+
+ Search::think();
+
+ assert(is_searching);
+ }
+}
+
+
+// Thread::notify_one() wakes up the thread, normally at the beginning of the
+// search or, if "sleeping threads" is used at split time.
+
+void Thread::notify_one() {
+
+ mutex.lock();
+ sleepCondition.notify_one();
+ mutex.unlock();
+}
+
+
+// Thread::wait_for_stop() is called when the maximum depth is reached while
+// the program is pondering. The point is to work around a wrinkle in the UCI
+// protocol: When pondering, the engine is not allowed to give a "bestmove"
+// before the GUI sends it a "stop" or "ponderhit" command. We simply wait here
+// until one of these commands (that raise Signals.stop) is sent and
+// then return, after which the bestmove and pondermove will be printed.
+
+void Thread::wait_for_stop() {
+
+ mutex.lock();
+ while (!Signals.stop) sleepCondition.wait(mutex);
+ mutex.unlock();
+}
+
+
+// Thread::cutoff_occurred() checks whether a beta cutoff has occurred in the
+// current active split point, or in some ancestor of the split point.