1 /*
2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2021 The Stockfish developers (see AUTHORS file)
4
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.
9
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.
14
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/>.
17 */
18
19 #include <cassert>
20
21 #include <algorithm> // For std::count
22 #include "movegen.h"
23 #include "search.h"
24 #include "thread.h"
25 #include "uci.h"
26 #include "syzygy/tbprobe.h"
27 #include "tt.h"
28
29 namespace Stockfish {
30
31 ThreadPool Threads; // Global object
32
33
34 /// Thread constructor launches the thread and waits until it goes to sleep
35 /// in idle_loop(). Note that 'searching' and 'exit' should be already set.
36
Thread(size_t n)37 Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) {
38
39 wait_for_search_finished();
40 }
41
42
43 /// Thread destructor wakes up the thread in idle_loop() and waits
44 /// for its termination. Thread should be already waiting.
45
~Thread()46 Thread::~Thread() {
47
48 assert(!searching);
49
50 exit = true;
51 start_searching();
52 stdThread.join();
53 }
54
55
56 /// Thread::clear() reset histories, usually before a new game
57
clear()58 void Thread::clear() {
59
60 counterMoves.fill(MOVE_NONE);
61 mainHistory.fill(0);
62 lowPlyHistory.fill(0);
63 captureHistory.fill(0);
64
65 for (bool inCheck : { false, true })
66 for (StatsType c : { NoCaptures, Captures })
67 {
68 for (auto& to : continuationHistory[inCheck][c])
69 for (auto& h : to)
70 h->fill(0);
71 continuationHistory[inCheck][c][NO_PIECE][0]->fill(Search::CounterMovePruneThreshold - 1);
72 }
73 }
74
75
76 /// Thread::start_searching() wakes up the thread that will start the search
77
start_searching()78 void Thread::start_searching() {
79
80 std::lock_guard<std::mutex> lk(mutex);
81 searching = true;
82 cv.notify_one(); // Wake up the thread in idle_loop()
83 }
84
85
86 /// Thread::wait_for_search_finished() blocks on the condition variable
87 /// until the thread has finished searching.
88
wait_for_search_finished()89 void Thread::wait_for_search_finished() {
90
91 std::unique_lock<std::mutex> lk(mutex);
92 cv.wait(lk, [&]{ return !searching; });
93 }
94
95
96 /// Thread::idle_loop() is where the thread is parked, blocked on the
97 /// condition variable, when it has no work to do.
98
idle_loop()99 void Thread::idle_loop() {
100
101 // If OS already scheduled us on a different group than 0 then don't overwrite
102 // the choice, eventually we are one of many one-threaded processes running on
103 // some Windows NUMA hardware, for instance in fishtest. To make it simple,
104 // just check if running threads are below a threshold, in this case all this
105 // NUMA machinery is not needed.
106 if (Options["Threads"] > 8)
107 WinProcGroup::bindThisThread(idx);
108
109 while (true)
110 {
111 std::unique_lock<std::mutex> lk(mutex);
112 searching = false;
113 cv.notify_one(); // Wake up anyone waiting for search finished
114 cv.wait(lk, [&]{ return searching; });
115
116 if (exit)
117 return;
118
119 lk.unlock();
120
121 search();
122 }
123 }
124
125 /// ThreadPool::set() creates/destroys threads to match the requested number.
126 /// Created and launched threads will immediately go to sleep in idle_loop.
127 /// Upon resizing, threads are recreated to allow for binding if necessary.
128
set(size_t requested)129 void ThreadPool::set(size_t requested) {
130
131 if (size() > 0) // destroy any existing thread(s)
132 {
133 main()->wait_for_search_finished();
134
135 while (size() > 0)
136 delete back(), pop_back();
137 }
138
139 if (requested > 0) // create new thread(s)
140 {
141 push_back(new MainThread(0));
142
143 while (size() < requested)
144 push_back(new Thread(size()));
145 clear();
146
147 // Reallocate the hash with the new threadpool size
148 TT.resize(size_t(Options["Hash"]));
149
150 // Init thread number dependent search params.
151 Search::init();
152 }
153 }
154
155
156 /// ThreadPool::clear() sets threadPool data to initial values
157
clear()158 void ThreadPool::clear() {
159
160 for (Thread* th : *this)
161 th->clear();
162
163 main()->callsCnt = 0;
164 main()->bestPreviousScore = VALUE_INFINITE;
165 main()->previousTimeReduction = 1.0;
166 }
167
168
169 /// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and
170 /// returns immediately. Main thread will wake up other threads and start the search.
171
start_thinking(Position & pos,StateListPtr & states,const Search::LimitsType & limits,bool ponderMode)172 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
173 const Search::LimitsType& limits, bool ponderMode) {
174
175 main()->wait_for_search_finished();
176
177 main()->stopOnPonderhit = stop = false;
178 increaseDepth = true;
179 main()->ponder = ponderMode;
180 Search::Limits = limits;
181 Search::RootMoves rootMoves;
182
183 for (const auto& m : MoveList<LEGAL>(pos))
184 if ( limits.searchmoves.empty()
185 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
186 rootMoves.emplace_back(m);
187
188 if (!rootMoves.empty())
189 Tablebases::rank_root_moves(pos, rootMoves);
190
191 // After ownership transfer 'states' becomes empty, so if we stop the search
192 // and call 'go' again without setting a new position states.get() == NULL.
193 assert(states.get() || setupStates.get());
194
195 if (states.get())
196 setupStates = std::move(states); // Ownership transfer, states is now empty
197
198 // We use Position::set() to set root position across threads. But there are
199 // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
200 // be deduced from a fen string, so set() clears them and they are set from
201 // setupStates->back() later. The rootState is per thread, earlier states are shared
202 // since they are read-only.
203 for (Thread* th : *this)
204 {
205 th->nodes = th->tbHits = th->nmpMinPly = th->bestMoveChanges = 0;
206 th->rootDepth = th->completedDepth = 0;
207 th->rootMoves = rootMoves;
208 th->rootPos.set(pos.fen(), pos.is_chess960(), &th->rootState, th);
209 th->rootState = setupStates->back();
210 }
211
212 main()->start_searching();
213 }
214
get_best_thread() const215 Thread* ThreadPool::get_best_thread() const {
216
217 Thread* bestThread = front();
218 std::map<Move, int64_t> votes;
219 Value minScore = VALUE_NONE;
220
221 // Find minimum score of all threads
222 for (Thread* th: *this)
223 minScore = std::min(minScore, th->rootMoves[0].score);
224
225 // Vote according to score and depth, and select the best thread
226 for (Thread* th : *this)
227 {
228 votes[th->rootMoves[0].pv[0]] +=
229 (th->rootMoves[0].score - minScore + 14) * int(th->completedDepth);
230
231 if (abs(bestThread->rootMoves[0].score) >= VALUE_TB_WIN_IN_MAX_PLY)
232 {
233 // Make sure we pick the shortest mate / TB conversion or stave off mate the longest
234 if (th->rootMoves[0].score > bestThread->rootMoves[0].score)
235 bestThread = th;
236 }
237 else if ( th->rootMoves[0].score >= VALUE_TB_WIN_IN_MAX_PLY
238 || ( th->rootMoves[0].score > VALUE_TB_LOSS_IN_MAX_PLY
239 && votes[th->rootMoves[0].pv[0]] > votes[bestThread->rootMoves[0].pv[0]]))
240 bestThread = th;
241 }
242
243 return bestThread;
244 }
245
246
247 /// Start non-main threads
248
start_searching()249 void ThreadPool::start_searching() {
250
251 for (Thread* th : *this)
252 if (th != front())
253 th->start_searching();
254 }
255
256
257 /// Wait for non-main threads
258
wait_for_search_finished() const259 void ThreadPool::wait_for_search_finished() const {
260
261 for (Thread* th : *this)
262 if (th != front())
263 th->wait_for_search_finished();
264 }
265
266 } // namespace Stockfish
267