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