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