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.
89 searching = resetCallsCnt = false;
90 maxPly = callsCnt = 0;
93 idx = Threads.size(); // Starts from 0
97 // Thread::idle_loop() is where the thread is parked when it has no work to do
99 void Thread::idle_loop() {
103 std::unique_lock<Mutex> lk(mutex);
105 while (!searching && !exit)
106 sleepCondition.wait(lk);
110 if (!exit && searching)
116 // MainThread::idle_loop() is where the main thread is parked waiting to be started
117 // when there is a new search. The main thread will launch all the slave threads.
119 void MainThread::idle_loop() {
123 std::unique_lock<Mutex> lk(mutex);
127 while (!thinking && !exit)
129 sleepCondition.notify_one(); // Wake up the UI thread if needed
130 sleepCondition.wait(lk);
141 // MainThread::join() waits for main thread to finish thinking
143 void MainThread::join() {
145 std::unique_lock<Mutex> lk(mutex);
146 sleepCondition.wait(lk, [&]{ return !thinking; });
150 // ThreadPool::init() is called at startup to create and launch requested threads,
151 // that will go immediately to sleep. We cannot use a constructor because Threads
152 // is a static object and we need a fully initialized engine at this point due to
153 // allocation of Endgames in the Thread constructor.
155 void ThreadPool::init() {
157 push_back(new_thread<MainThread>());
162 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
163 // done in destructor because threads must be terminated before freeing us.
165 void ThreadPool::exit() {
167 for (Thread* th : *this)
170 clear(); // Get rid of stale pointers
174 // ThreadPool::read_uci_options() updates internal threads parameters from the
175 // corresponding UCI options and creates/destroys threads to match the requested
176 // number. Thread objects are dynamically allocated to avoid creating all possible
177 // threads in advance (which include pawns and material tables), even if only a
178 // few are to be used.
180 void ThreadPool::read_uci_options() {
182 size_t requested = Options["Threads"];
184 assert(requested > 0);
186 while (size() < requested)
187 push_back(new_thread<Thread>());
189 while (size() > requested)
191 delete_thread(back());
197 // ThreadPool::nodes_searched() returns the number of nodes searched
199 int64_t ThreadPool::nodes_searched() {
202 for (Thread *th : *this)
203 nodes += th->rootPos.nodes_searched();
208 // ThreadPool::start_thinking() wakes up the main thread sleeping in
209 // MainThread::idle_loop() and starts a new search, then returns immediately.
211 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
212 StateStackPtr& states) {
215 Signals.stopOnPonderhit = Signals.firstRootMove = false;
216 Signals.stop = Signals.failedLowAtRoot = false;
218 main()->rootMoves.clear();
219 main()->rootPos = pos;
221 if (states.get()) // If we don't set a new position, preserve current state
223 SetupStates = std::move(states); // Ownership transfer here
224 assert(!states.get());
227 for (const auto& m : MoveList<LEGAL>(pos))
228 if ( limits.searchmoves.empty()
229 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
230 main()->rootMoves.push_back(RootMove(m));
232 main()->thinking = true;
233 main()->notify_one(); // Wake up main thread: 'thinking' must be already set