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