2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2023 The Stockfish developers (see AUTHORS file)
5 Stockfish is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Stockfish is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include <initializer_list>
34 #include "syzygy/tbprobe.h"
40 ThreadPool Threads; // Global object
43 /// Thread constructor launches the thread and waits until it goes to sleep
44 /// in idle_loop(). Note that 'searching' and 'exit' should be already set.
46 Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) {
48 wait_for_search_finished();
52 /// Thread destructor wakes up the thread in idle_loop() and waits
53 /// for its termination. Thread should be already waiting.
65 /// Thread::clear() reset histories, usually before a new game
67 void Thread::clear() {
69 counterMoves.fill(MOVE_NONE);
71 captureHistory.fill(0);
73 for (bool inCheck : { false, true })
74 for (StatsType c : { NoCaptures, Captures })
75 for (auto& to : continuationHistory[inCheck][c])
81 /// Thread::start_searching() wakes up the thread that will start the search
83 void Thread::start_searching() {
86 mutex.unlock(); // Unlock before notifying saves a few CPU-cycles
87 cv.notify_one(); // Wake up the thread in idle_loop()
91 /// Thread::wait_for_search_finished() blocks on the condition variable
92 /// until the thread has finished searching.
94 void Thread::wait_for_search_finished() {
96 std::unique_lock<std::mutex> lk(mutex);
97 cv.wait(lk, [&]{ return !searching; });
101 /// Thread::idle_loop() is where the thread is parked, blocked on the
102 /// condition variable, when it has no work to do.
104 void Thread::idle_loop() {
106 // If OS already scheduled us on a different group than 0 then don't overwrite
107 // the choice, eventually we are one of many one-threaded processes running on
108 // some Windows NUMA hardware, for instance in fishtest. To make it simple,
109 // just check if running threads are below a threshold, in this case all this
110 // NUMA machinery is not needed.
111 if (Options["Threads"] > 8)
112 WinProcGroup::bindThisThread(idx);
116 std::unique_lock<std::mutex> lk(mutex);
118 cv.notify_one(); // Wake up anyone waiting for search finished
119 cv.wait(lk, [&]{ return searching; });
130 /// ThreadPool::set() creates/destroys threads to match the requested number.
131 /// Created and launched threads will immediately go to sleep in idle_loop.
132 /// Upon resizing, threads are recreated to allow for binding if necessary.
134 void ThreadPool::set(size_t requested) {
136 if (threads.size() > 0) // destroy any existing thread(s)
138 main()->wait_for_search_finished();
140 while (threads.size() > 0)
141 delete threads.back(), threads.pop_back();
144 if (requested > 0) // create new thread(s)
146 threads.push_back(new MainThread(0));
148 while (threads.size() < requested)
149 threads.push_back(new Thread(threads.size()));
152 // Reallocate the hash with the new threadpool size
153 TT.resize(size_t(Options["Hash"]));
155 // Init thread number dependent search params.
161 /// ThreadPool::clear() sets threadPool data to initial values
163 void ThreadPool::clear() {
165 for (Thread* th : threads)
168 main()->callsCnt = 0;
169 main()->bestPreviousScore = VALUE_INFINITE;
170 main()->bestPreviousAverageScore = VALUE_INFINITE;
171 main()->previousTimeReduction = 1.0;
175 /// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and
176 /// returns immediately. Main thread will wake up other threads and start the search.
178 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
179 const Search::LimitsType& limits, bool ponderMode) {
181 main()->wait_for_search_finished();
183 main()->stopOnPonderhit = stop = false;
184 increaseDepth = true;
185 main()->ponder = ponderMode;
186 Search::Limits = limits;
187 Search::RootMoves rootMoves;
189 for (const auto& m : MoveList<LEGAL>(pos))
190 if ( limits.searchmoves.empty()
191 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
192 rootMoves.emplace_back(m);
194 if (!rootMoves.empty())
195 Tablebases::rank_root_moves(pos, rootMoves);
197 // After ownership transfer 'states' becomes empty, so if we stop the search
198 // and call 'go' again without setting a new position states.get() == nullptr.
199 assert(states.get() || setupStates.get());
202 setupStates = std::move(states); // Ownership transfer, states is now empty
204 // We use Position::set() to set root position across threads. But there are
205 // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
206 // be deduced from a fen string, so set() clears them and they are set from
207 // setupStates->back() later. The rootState is per thread, earlier states are shared
208 // since they are read-only.
209 for (Thread* th : threads)
211 th->nodes = th->tbHits = th->nmpMinPly = th->bestMoveChanges = 0;
212 th->rootDepth = th->completedDepth = 0;
213 th->rootMoves = rootMoves;
214 th->rootPos.set(pos.fen(), pos.is_chess960(), &th->rootState, th);
215 th->rootState = setupStates->back();
216 th->rootSimpleEval = Eval::simple_eval(pos, pos.side_to_move());
219 main()->start_searching();
222 Thread* ThreadPool::get_best_thread() const {
224 Thread* bestThread = threads.front();
225 std::map<Move, int64_t> votes;
226 Value minScore = VALUE_NONE;
228 // Find minimum score of all threads
229 for (Thread* th: threads)
230 minScore = std::min(minScore, th->rootMoves[0].score);
232 // Vote according to score and depth, and select the best thread
233 auto thread_value = [minScore](Thread* th) {
234 return (th->rootMoves[0].score - minScore + 14) * int(th->completedDepth);
237 for (Thread* th : threads)
238 votes[th->rootMoves[0].pv[0]] += thread_value(th);
240 for (Thread* th : threads)
241 if (abs(bestThread->rootMoves[0].score) >= VALUE_TB_WIN_IN_MAX_PLY)
243 // Make sure we pick the shortest mate / TB conversion or stave off mate the longest
244 if (th->rootMoves[0].score > bestThread->rootMoves[0].score)
247 else if ( th->rootMoves[0].score >= VALUE_TB_WIN_IN_MAX_PLY
248 || ( th->rootMoves[0].score > VALUE_TB_LOSS_IN_MAX_PLY
249 && ( votes[th->rootMoves[0].pv[0]] > votes[bestThread->rootMoves[0].pv[0]]
250 || ( votes[th->rootMoves[0].pv[0]] == votes[bestThread->rootMoves[0].pv[0]]
251 && thread_value(th) * int(th->rootMoves[0].pv.size() > 2)
252 > thread_value(bestThread) * int(bestThread->rootMoves[0].pv.size() > 2)))))
259 /// Start non-main threads
261 void ThreadPool::start_searching() {
263 for (Thread* th : threads)
264 if (th != threads.front())
265 th->start_searching();
269 /// Wait for non-main threads
271 void ThreadPool::wait_for_search_finished() const {
273 for (Thread* th : threads)
274 if (th != threads.front())
275 th->wait_for_search_finished();
278 } // namespace Stockfish