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