2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2020 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/>.
21 #include <algorithm> // For std::count
26 #include "syzygy/tbprobe.h"
29 ThreadPool Threads; // Global object
32 /// Thread constructor launches the thread and waits until it goes to sleep
33 /// in idle_loop(). Note that 'searching' and 'exit' should be already set.
35 Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) {
37 wait_for_search_finished();
41 /// Thread destructor wakes up the thread in idle_loop() and waits
42 /// for its termination. Thread should be already waiting.
54 /// Thread::clear() reset histories, usually before a new game
56 void Thread::clear() {
58 counterMoves.fill(MOVE_NONE);
60 staticHistory.fill(0);
61 lowPlyHistory.fill(0);
62 captureHistory.fill(0);
64 for (bool inCheck : { false, true })
65 for (StatsType c : { NoCaptures, Captures })
67 for (auto& to : continuationHistory[inCheck][c])
70 continuationHistory[inCheck][c][NO_PIECE][0]->fill(Search::CounterMovePruneThreshold - 1);
75 /// Thread::start_searching() wakes up the thread that will start the search
77 void Thread::start_searching() {
79 std::lock_guard<std::mutex> lk(mutex);
81 cv.notify_one(); // Wake up the thread in idle_loop()
85 /// Thread::wait_for_search_finished() blocks on the condition variable
86 /// until the thread has finished searching.
88 void Thread::wait_for_search_finished() {
90 std::unique_lock<std::mutex> lk(mutex);
91 cv.wait(lk, [&]{ return !searching; });
95 /// Thread::idle_loop() is where the thread is parked, blocked on the
96 /// condition variable, when it has no work to do.
98 void Thread::idle_loop() {
100 // If OS already scheduled us on a different group than 0 then don't overwrite
101 // the choice, eventually we are one of many one-threaded processes running on
102 // some Windows NUMA hardware, for instance in fishtest. To make it simple,
103 // just check if running threads are below a threshold, in this case all this
104 // NUMA machinery is not needed.
105 if (Options["Threads"] > 8)
106 WinProcGroup::bindThisThread(idx);
110 std::unique_lock<std::mutex> lk(mutex);
112 cv.notify_one(); // Wake up anyone waiting for search finished
113 cv.wait(lk, [&]{ return searching; });
124 /// ThreadPool::set() creates/destroys threads to match the requested number.
125 /// Created and launched threads will immediately go to sleep in idle_loop.
126 /// Upon resizing, threads are recreated to allow for binding if necessary.
128 void ThreadPool::set(size_t requested) {
130 if (size() > 0) { // destroy any existing thread(s)
131 main()->wait_for_search_finished();
134 delete back(), pop_back();
137 if (requested > 0) { // create new thread(s)
138 push_back(new MainThread(0));
140 while (size() < requested)
141 push_back(new Thread(size()));
144 // Reallocate the hash with the new threadpool size
145 TT.resize(size_t(Options["Hash"]));
147 // Init thread number dependent search params.
153 /// ThreadPool::clear() sets threadPool data to initial values
155 void ThreadPool::clear() {
157 for (Thread* th : *this)
160 main()->callsCnt = 0;
161 main()->bestPreviousScore = VALUE_INFINITE;
162 main()->previousTimeReduction = 1.0;
166 /// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and
167 /// returns immediately. Main thread will wake up other threads and start the search.
169 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
170 const Search::LimitsType& limits, bool ponderMode) {
172 main()->wait_for_search_finished();
174 main()->stopOnPonderhit = stop = false;
175 increaseDepth = true;
176 main()->ponder = ponderMode;
177 Search::Limits = limits;
178 Search::RootMoves rootMoves;
180 for (const auto& m : MoveList<LEGAL>(pos))
181 if ( limits.searchmoves.empty()
182 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
183 rootMoves.emplace_back(m);
185 if (!rootMoves.empty())
186 Tablebases::rank_root_moves(pos, rootMoves);
188 // After ownership transfer 'states' becomes empty, so if we stop the search
189 // and call 'go' again without setting a new position states.get() == NULL.
190 assert(states.get() || setupStates.get());
193 setupStates = std::move(states); // Ownership transfer, states is now empty
195 // We use Position::set() to set root position across threads. But there are
196 // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
197 // be deduced from a fen string, so set() clears them and they are set from
198 // setupStates->back() later. The rootState is per thread, earlier states are shared
199 // since they are read-only.
200 for (Thread* th : *this)
202 th->nodes = th->tbHits = th->nmpMinPly = th->bestMoveChanges = 0;
203 th->rootDepth = th->completedDepth = 0;
204 th->rootMoves = rootMoves;
205 th->rootPos.set(pos.fen(), pos.is_chess960(), &th->rootState, th);
206 th->rootState = setupStates->back();
209 main()->start_searching();
212 Thread* ThreadPool::get_best_thread() const {
214 Thread* bestThread = front();
215 std::map<Move, int64_t> votes;
216 Value minScore = VALUE_NONE;
218 // Find minimum score of all threads
219 for (Thread* th: *this)
220 minScore = std::min(minScore, th->rootMoves[0].score);
222 // Vote according to score and depth, and select the best thread
223 for (Thread* th : *this)
225 votes[th->rootMoves[0].pv[0]] +=
226 (th->rootMoves[0].score - minScore + 14) * int(th->completedDepth);
228 if (abs(bestThread->rootMoves[0].score) >= VALUE_TB_WIN_IN_MAX_PLY)
230 // Make sure we pick the shortest mate / TB conversion or stave off mate the longest
231 if (th->rootMoves[0].score > bestThread->rootMoves[0].score)
234 else if ( th->rootMoves[0].score >= VALUE_TB_WIN_IN_MAX_PLY
235 || ( th->rootMoves[0].score > VALUE_TB_LOSS_IN_MAX_PLY
236 && votes[th->rootMoves[0].pv[0]] > votes[bestThread->rootMoves[0].pv[0]]))
244 /// Start non-main threads
246 void ThreadPool::start_searching() {
248 for (Thread* th : *this)
250 th->start_searching();
254 /// Wait for non-main threads
256 void ThreadPool::wait_for_search_finished() const {
258 for (Thread* th : *this)
260 th->wait_for_search_finished();