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