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