+// Thread c'tor creates and launches the OS thread, that will go immediately to
+// sleep.
+
+Thread::Thread(int id) {
+
+ is_searching = do_exit = false;
+ maxPly = splitPointsCnt = 0;
+ curSplitPoint = NULL;
+ threadID = id;
+ do_sleep = (id != 0); // Avoid a race with start_thinking()
+
+ lock_init(sleepLock);
+ cond_init(sleepCond);
+
+ for (int j = 0; j < MAX_SPLITPOINTS_PER_THREAD; j++)
+ lock_init(splitPoints[j].lock);
+
+ if (!thread_create(handle, start_routine, this))
+ {
+ std::cerr << "Failed to create thread number " << id << std::endl;
+ ::exit(EXIT_FAILURE);
+ }
+}
+
+
+// Thread d'tor will wait 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
+
+ lock_destroy(sleepLock);
+ cond_destroy(sleepCond);
+
+ for (int j = 0; j < MAX_SPLITPOINTS_PER_THREAD; j++)
+ lock_destroy(splitPoints[j].lock);
+}
+
+
+// Thread::timer_loop() is where the timer thread waits maxPly milliseconds and
+// then calls do_timer_event(). If maxPly is 0 thread sleeps until is woken up.
+extern void check_time();
+
+void Thread::timer_loop() {
+
+ while (!do_exit)
+ {
+ lock_grab(sleepLock);
+ timed_wait(sleepCond, sleepLock, maxPly ? maxPly : INT_MAX);
+ lock_release(sleepLock);
+ 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)
+ {
+ lock_grab(sleepLock);
+
+ do_sleep = true; // Always return to sleep after a search
+ is_searching = false;
+
+ while (do_sleep && !do_exit)
+ {
+ cond_signal(Threads.sleepCond); // Wake up UI thread if needed
+ cond_wait(sleepCond, sleepLock);
+ }
+
+ lock_release(sleepLock);
+
+ if (do_exit)
+ return;
+
+ is_searching = true;
+
+ Search::think();
+ }
+}
+
+
+// Thread::wake_up() wakes up the thread, normally at the beginning of the search
+// or, if "sleeping threads" is used, when there is some work to do.