2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <algorithm> // For std::count
28 using namespace Search;
30 ThreadPool Threads; // Global object
34 // Helpers to launch a thread after creation and joining before delete. Outside the
35 // Thread constructor and destructor because the object must be fully initialized
36 // when start_routine (and hence virtual idle_loop) is called and when joining.
38 template<typename T> T* new_thread() {
39 std::thread* th = new T;
40 *th = std::thread(&T::idle_loop, (T*)th); // Will go to sleep
44 void delete_thread(ThreadBase* th) {
47 th->exit = true; // Search must be already finished
51 th->join(); // Wait for thread termination
58 // ThreadBase::notify_one() wakes up the thread when there is some work to do
60 void ThreadBase::notify_one() {
62 std::unique_lock<Mutex> lk(mutex);
63 sleepCondition.notify_one();
67 // ThreadBase::wait() set the thread to sleep until 'condition' turns true
69 void ThreadBase::wait(std::atomic<bool>& condition) {
71 std::unique_lock<Mutex> lk(mutex);
72 sleepCondition.wait(lk, [&]{ return bool(condition); });
76 // ThreadBase::wait_while() set the thread to sleep until 'condition' turns false
77 void ThreadBase::wait_while(std::atomic<bool>& condition) {
79 std::unique_lock<Mutex> lk(mutex);
80 sleepCondition.wait(lk, [&]{ return !condition; });
84 // Thread constructor makes some init but does not launch any execution thread,
85 // which will be started only when the constructor returns.
93 idx = Threads.size(); // Starts from 0
97 // TimerThread::idle_loop() is where the timer thread waits Resolution milliseconds
98 // and then calls check_time(). When not searching, thread sleeps until it's woken up.
100 void TimerThread::idle_loop() {
104 std::unique_lock<Mutex> lk(mutex);
107 sleepCondition.wait_for(lk, std::chrono::milliseconds(run ? Resolution : INT_MAX));
117 // Thread::idle_loop() is where the thread is parked when it has no work to do
119 void Thread::idle_loop() {
123 std::unique_lock<Mutex> lk(mutex);
125 while (!searching && !exit)
126 sleepCondition.wait(lk);
130 if (!exit && searching)
136 // MainThread::idle_loop() is where the main thread is parked waiting to be started
137 // when there is a new search. The main thread will launch all the slave threads.
139 void MainThread::idle_loop() {
143 std::unique_lock<Mutex> lk(mutex);
147 while (!thinking && !exit)
149 sleepCondition.notify_one(); // Wake up the UI thread if needed
150 sleepCondition.wait(lk);
161 // MainThread::join() waits for main thread to finish thinking
163 void MainThread::join() {
165 std::unique_lock<Mutex> lk(mutex);
166 sleepCondition.wait(lk, [&]{ return !thinking; });
170 // ThreadPool::init() is called at startup to create and launch requested threads,
171 // that will go immediately to sleep. We cannot use a constructor because Threads
172 // is a static object and we need a fully initialized engine at this point due to
173 // allocation of Endgames in the Thread constructor.
175 void ThreadPool::init() {
177 timer = new_thread<TimerThread>();
178 push_back(new_thread<MainThread>());
183 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
184 // done in destructor because threads must be terminated before freeing us.
186 void ThreadPool::exit() {
188 delete_thread(timer); // As first because check_time() accesses threads data
191 for (Thread* th : *this)
194 clear(); // Get rid of stale pointers
198 // ThreadPool::read_uci_options() updates internal threads parameters from the
199 // corresponding UCI options and creates/destroys threads to match the requested
200 // number. Thread objects are dynamically allocated to avoid creating all possible
201 // threads in advance (which include pawns and material tables), even if only a
202 // few are to be used.
204 void ThreadPool::read_uci_options() {
206 size_t requested = Options["Threads"];
208 assert(requested > 0);
210 while (size() < requested)
211 push_back(new_thread<Thread>());
213 while (size() > requested)
215 delete_thread(back());
221 // ThreadPool::nodes_searched() returns the number of nodes searched
223 int64_t ThreadPool::nodes_searched() {
226 for (Thread *th : *this)
227 nodes += th->rootPos.nodes_searched();
232 // ThreadPool::start_thinking() wakes up the main thread sleeping in
233 // MainThread::idle_loop() and starts a new search, then returns immediately.
235 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
236 StateStackPtr& states) {
239 Signals.stopOnPonderhit = Signals.firstRootMove = false;
240 Signals.stop = Signals.failedLowAtRoot = false;
242 main()->rootMoves.clear();
243 main()->rootPos = pos;
245 if (states.get()) // If we don't set a new position, preserve current state
247 SetupStates = std::move(states); // Ownership transfer here
248 assert(!states.get());
251 for (const auto& m : MoveList<LEGAL>(pos))
252 if ( limits.searchmoves.empty()
253 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
254 main()->rootMoves.push_back(RootMove(m));
256 main()->thinking = true;
257 main()->notify_one(); // Wake up main thread: 'thinking' must be already set