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
32 extern void check_time();
36 // Helpers to launch a thread after creation and joining before delete. Must be
37 // outside Thread c'tor and d'tor because the object must be fully initialized
38 // when start_routine (and hence virtual idle_loop) is called and when joining.
40 template<typename T> T* new_thread() {
41 std::thread* th = new T;
42 *th = std::thread(&T::idle_loop, (T*)th); // Will go to sleep
46 void delete_thread(ThreadBase* th) {
49 th->exit = true; // Search must be already finished
53 th->join(); // Wait for thread termination
60 // ThreadBase::notify_one() wakes up the thread when there is some work to do
62 void ThreadBase::notify_one() {
64 std::unique_lock<Mutex> lk(mutex);
65 sleepCondition.notify_one();
69 // ThreadBase::wait() set the thread to sleep until 'condition' turns true
71 void ThreadBase::wait(volatile const bool& condition) {
73 std::unique_lock<Mutex> lk(mutex);
74 sleepCondition.wait(lk, [&]{ return condition; });
78 // ThreadBase::wait_while() set the thread to sleep until 'condition' turns false
80 void ThreadBase::wait_while(volatile const bool& condition) {
82 std::unique_lock<Mutex> lk(mutex);
83 sleepCondition.wait(lk, [&]{ return !condition; });
87 // Thread c'tor makes some init but does not launch any execution thread that
88 // will be started only when c'tor returns.
90 Thread::Thread() /* : splitPoints() */ { // Initialization of non POD broken in MSVC
94 idx = Threads.size(); // Starts from 0
98 // TimerThread::idle_loop() is where the timer thread waits Resolution milliseconds
99 // and then calls check_time(). When not searching, thread sleeps until it's woken up.
101 void TimerThread::idle_loop() {
105 std::unique_lock<Mutex> lk(mutex);
108 sleepCondition.wait_for(lk, std::chrono::milliseconds(run ? Resolution : INT_MAX));
118 // Thread::idle_loop() is where the thread is parked when it has no work to do
120 void Thread::idle_loop() {
124 std::unique_lock<Mutex> lk(mutex);
126 while (!searching && !exit)
127 sleepCondition.wait(lk);
131 if (!exit && searching)
137 // MainThread::idle_loop() is where the main thread is parked waiting to be started
138 // when there is a new search. The main thread will launch all the slave threads.
140 void MainThread::idle_loop() {
144 std::unique_lock<Mutex> lk(mutex);
148 while (!thinking && !exit)
150 sleepCondition.notify_one(); // Wake up the UI thread if needed
151 sleepCondition.wait(lk);
162 // MainThread::join() waits for main thread to finish thinking
164 void MainThread::join() {
166 std::unique_lock<Mutex> lk(mutex);
167 sleepCondition.wait(lk, [&]{ return !thinking; });
171 // ThreadPool::init() is called at startup to create and launch requested threads,
172 // that will go immediately to sleep. We cannot use a c'tor because Threads is a
173 // static object and we need a fully initialized engine at this point due to
174 // allocation of Endgames in Thread c'tor.
176 void ThreadPool::init() {
178 timer = new_thread<TimerThread>();
179 push_back(new_thread<MainThread>());
184 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
185 // done in d'tor because threads must be terminated before freeing us.
187 void ThreadPool::exit() {
189 delete_thread(timer); // As first because check_time() accesses threads data
192 for (Thread* th : *this)
195 clear(); // Get rid of stale pointers
199 // ThreadPool::read_uci_options() updates internal threads parameters from the
200 // corresponding UCI options and creates/destroys threads to match the requested
201 // number. Thread objects are dynamically allocated to avoid creating all possible
202 // threads in advance (which include pawns and material tables), even if only a
203 // few are to be used.
205 void ThreadPool::read_uci_options() {
207 size_t requested = Options["Threads"];
209 assert(requested > 0);
211 while (size() < requested)
212 push_back(new_thread<Thread>());
214 while (size() > requested)
216 delete_thread(back());
222 // ThreadPool::nodes_searched() returns the number of nodes searched
224 int64_t ThreadPool::nodes_searched() {
227 for (Thread *th : *this)
228 nodes += th->rootPos.nodes_searched();
233 // ThreadPool::start_thinking() wakes up the main thread sleeping in
234 // MainThread::idle_loop() and starts a new search, then returns immediately.
236 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
237 StateStackPtr& states) {
240 Signals.stopOnPonderhit = Signals.firstRootMove = false;
241 Signals.stop = Signals.failedLowAtRoot = false;
243 main()->rootMoves.clear();
244 main()->rootPos = pos;
246 if (states.get()) // If we don't set a new position, preserve current state
248 SetupStates = std::move(states); // Ownership transfer here
249 assert(!states.get());
252 for (const auto& m : MoveList<LEGAL>(pos))
253 if ( limits.searchmoves.empty()
254 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
255 main()->rootMoves.push_back(RootMove(m));
257 main()->thinking = true;
258 main()->notify_one(); // Wake up main thread: 'thinking' must be already set