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
5 Copyright (C) 2015-2019 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
7 Stockfish is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 Stockfish is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #include "syzygy/tbprobe.h"
30 ThreadPool Threads; // Global object
33 /// Thread constructor launches the thread and waits until it goes to sleep
34 /// in idle_loop(). Note that 'searching' and 'exit' should be already set.
36 Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) {
38 wait_for_search_finished();
42 /// Thread destructor wakes up the thread in idle_loop() and waits
43 /// for its termination. Thread should be already waiting.
55 /// Thread::clear() reset histories, usually before a new game
57 void Thread::clear() {
59 counterMoves.fill(MOVE_NONE);
61 captureHistory.fill(0);
63 for (auto& to : continuationHistory)
67 continuationHistory[NO_PIECE][0]->fill(Search::CounterMovePruneThreshold - 1);
70 /// Thread::start_searching() wakes up the thread that will start the search
72 void Thread::start_searching() {
74 std::lock_guard<Mutex> lk(mutex);
76 cv.notify_one(); // Wake up the thread in idle_loop()
80 /// Thread::wait_for_search_finished() blocks on the condition variable
81 /// until the thread has finished searching.
83 void Thread::wait_for_search_finished() {
85 std::unique_lock<Mutex> lk(mutex);
86 cv.wait(lk, [&]{ return !searching; });
90 /// Thread::idle_loop() is where the thread is parked, blocked on the
91 /// condition variable, when it has no work to do.
93 void Thread::idle_loop() {
95 // If OS already scheduled us on a different group than 0 then don't overwrite
96 // the choice, eventually we are one of many one-threaded processes running on
97 // some Windows NUMA hardware, for instance in fishtest. To make it simple,
98 // just check if running threads are below a threshold, in this case all this
99 // NUMA machinery is not needed.
100 if (Options["Threads"] > 8)
101 WinProcGroup::bindThisThread(idx);
105 std::unique_lock<Mutex> lk(mutex);
107 cv.notify_one(); // Wake up anyone waiting for search finished
108 cv.wait(lk, [&]{ return searching; });
119 /// ThreadPool::set() creates/destroys threads to match the requested number.
120 /// Created and launched threads will immediately go to sleep in idle_loop.
121 /// Upon resizing, threads are recreated to allow for binding if necessary.
123 void ThreadPool::set(size_t requested) {
125 if (size() > 0) { // destroy any existing thread(s)
126 main()->wait_for_search_finished();
129 delete back(), pop_back();
132 if (requested > 0) { // create new thread(s)
133 push_back(new MainThread(0));
135 while (size() < requested)
136 push_back(new Thread(size()));
139 // Reallocate the hash with the new threadpool size
140 TT.resize(Options["Hash"]);
144 /// ThreadPool::clear() sets threadPool data to initial values.
146 void ThreadPool::clear() {
148 for (Thread* th : *this)
151 main()->callsCnt = 0;
152 main()->previousScore = VALUE_INFINITE;
153 main()->previousTimeReduction = 1.0;
156 /// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and
157 /// returns immediately. Main thread will wake up other threads and start the search.
159 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
160 const Search::LimitsType& limits, bool ponderMode) {
162 main()->wait_for_search_finished();
164 main()->stopOnPonderhit = stop = false;
165 main()->ponder = ponderMode;
166 Search::Limits = limits;
167 Search::RootMoves rootMoves;
169 for (const auto& m : MoveList<LEGAL>(pos))
170 if ( limits.searchmoves.empty()
171 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
172 rootMoves.emplace_back(m);
174 if (!rootMoves.empty())
175 Tablebases::rank_root_moves(pos, rootMoves);
177 // After ownership transfer 'states' becomes empty, so if we stop the search
178 // and call 'go' again without setting a new position states.get() == NULL.
179 assert(states.get() || setupStates.get());
182 setupStates = std::move(states); // Ownership transfer, states is now empty
184 // We use Position::set() to set root position across threads. But there are
185 // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
186 // be deduced from a fen string, so set() clears them and to not lose the info
187 // we need to backup and later restore setupStates->back(). Note that setupStates
188 // is shared by threads but is accessed in read-only mode.
189 StateInfo tmp = setupStates->back();
191 for (Thread* th : *this)
193 th->nodes = th->tbHits = th->nmpMinPly = 0;
194 th->rootDepth = th->completedDepth = DEPTH_ZERO;
195 th->rootMoves = rootMoves;
196 th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th);
199 setupStates->back() = tmp;
201 main()->start_searching();