+// Thread d'tor waits for thread termination before to return.
+
+Thread::~Thread() {
+
+ assert(do_sleep);
+
+ do_exit = true; // Search must be already finished
+ wake_up();
+ thread_join(handle); // Wait for thread termination
+}
+
+
+// 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();