]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Updated KNNKP endgame.
[stockfish] / src / thread.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2020 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include <algorithm> // For std::count
24 #include "movegen.h"
25 #include "search.h"
26 #include "thread.h"
27 #include "uci.h"
28 #include "syzygy/tbprobe.h"
29 #include "tt.h"
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 /// Thread::bestMoveCount(Move move) return best move counter for the given root move
56
57 int Thread::best_move_count(Move move) const {
58
59   auto rm = std::find(rootMoves.begin() + pvIdx,
60                       rootMoves.begin() + pvLast, move);
61
62   return rm != rootMoves.begin() + pvLast ? rm->bestMoveCount : 0;
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   captureHistory.fill(0);
72
73   for (bool inCheck : { false, true })
74       for (StatsType c : { NoCaptures, Captures })
75       {
76           for (auto& to : continuationHistory[inCheck][c])
77                 for (auto& h : to)
78                       h->fill(0);
79           continuationHistory[inCheck][c][NO_PIECE][0]->fill(Search::CounterMovePruneThreshold - 1);
80       }
81 }
82
83 /// Thread::start_searching() wakes up the thread that will start the search
84
85 void Thread::start_searching() {
86
87   std::lock_guard<std::mutex> lk(mutex);
88   searching = true;
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 (size() > 0) { // destroy any existing thread(s)
139       main()->wait_for_search_finished();
140
141       while (size() > 0)
142           delete back(), pop_back();
143   }
144
145   if (requested > 0) { // create new thread(s)
146       push_back(new MainThread(0));
147
148       while (size() < requested)
149           push_back(new Thread(size()));
150       clear();
151
152       // Reallocate the hash with the new threadpool size
153       TT.resize(Options["Hash"]);
154
155       // Init thread number dependent search params.
156       Search::init();
157   }
158 }
159
160 /// ThreadPool::clear() sets threadPool data to initial values.
161
162 void ThreadPool::clear() {
163
164   for (Thread* th : *this)
165       th->clear();
166
167   main()->callsCnt = 0;
168   main()->previousScore = VALUE_INFINITE;
169   main()->previousTimeReduction = 1.0;
170 }
171
172 /// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and
173 /// returns immediately. Main thread will wake up other threads and start the search.
174
175 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
176                                 const Search::LimitsType& limits, 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() == NULL.
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 to not lose the info
204   // we need to backup and later restore setupStates->back(). Note that setupStates
205   // is shared by threads but is accessed in read-only mode.
206   StateInfo tmp = setupStates->back();
207
208   for (Thread* th : *this)
209   {
210       th->nodes = th->tbHits = th->nmpMinPly = 0;
211       th->rootDepth = th->completedDepth = 0;
212       th->rootMoves = rootMoves;
213       th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th);
214   }
215
216   setupStates->back() = tmp;
217
218   main()->start_searching();
219 }