]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Cleanup history stats
[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
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <algorithm> // For std::count
21 #include <cassert>
22
23 #include "movegen.h"
24 #include "search.h"
25 #include "thread.h"
26 #include "uci.h"
27
28 using namespace Search;
29
30 ThreadPool Threads; // Global object
31
32 extern void check_time();
33
34 namespace {
35
36  // Helpers to launch a thread after creation and joining before delete. Must be
37  // outside Thread c'tor and d'tor because the object must be fully initialized
38  // when start_routine (and hence virtual idle_loop) is called and when joining.
39
40  template<typename T> T* new_thread() {
41    std::thread* th = new T;
42    *th = std::thread(&T::idle_loop, (T*)th); // Will go to sleep
43    return (T*)th;
44  }
45
46  void delete_thread(ThreadBase* th) {
47
48    th->mutex.lock();
49    th->exit = true; // Search must be already finished
50    th->mutex.unlock();
51
52    th->notify_one();
53    th->join(); // Wait for thread termination
54    delete th;
55  }
56
57 }
58
59
60 // ThreadBase::notify_one() wakes up the thread when there is some work to do
61
62 void ThreadBase::notify_one() {
63
64   std::unique_lock<Mutex> lk(mutex);
65   sleepCondition.notify_one();
66 }
67
68
69 // ThreadBase::wait() set the thread to sleep until 'condition' turns true
70
71 void ThreadBase::wait(volatile const bool& condition) {
72
73   std::unique_lock<Mutex> lk(mutex);
74   sleepCondition.wait(lk, [&]{ return condition; });
75 }
76
77
78 // ThreadBase::wait_while() set the thread to sleep until 'condition' turns false
79
80 void ThreadBase::wait_while(volatile const bool& condition) {
81
82   std::unique_lock<Mutex> lk(mutex);
83   sleepCondition.wait(lk, [&]{ return !condition; });
84 }
85
86
87 // Thread c'tor makes some init but does not launch any execution thread that
88 // will be started only when c'tor returns.
89
90 Thread::Thread() /* : splitPoints() */ { // Initialization of non POD broken in MSVC
91
92   searching = false;
93   maxPly = 0;
94   history.clear();
95   counterMoves.clear();
96   idx = Threads.size(); // Starts from 0
97 }
98
99
100 // TimerThread::idle_loop() is where the timer thread waits Resolution milliseconds
101 // and then calls check_time(). When not searching, thread sleeps until it's woken up.
102
103 void TimerThread::idle_loop() {
104
105   while (!exit)
106   {
107       std::unique_lock<Mutex> lk(mutex);
108
109       if (!exit)
110           sleepCondition.wait_for(lk, std::chrono::milliseconds(run ? Resolution : INT_MAX));
111
112       lk.unlock();
113
114       if (!exit && run)
115           check_time();
116   }
117 }
118
119
120 // Thread::idle_loop() is where the thread is parked when it has no work to do
121
122 void Thread::idle_loop() {
123
124   while (!exit)
125   {
126       std::unique_lock<Mutex> lk(mutex);
127
128       while (!searching && !exit)
129           sleepCondition.wait(lk);
130
131       lk.unlock();
132
133       if (!exit && searching)
134           search();
135   }
136 }
137
138
139 // MainThread::idle_loop() is where the main thread is parked waiting to be started
140 // when there is a new search. The main thread will launch all the slave threads.
141
142 void MainThread::idle_loop() {
143
144   while (!exit)
145   {
146       std::unique_lock<Mutex> lk(mutex);
147
148       thinking = false;
149
150       while (!thinking && !exit)
151       {
152           sleepCondition.notify_one(); // Wake up the UI thread if needed
153           sleepCondition.wait(lk);
154       }
155
156       lk.unlock();
157
158       if (!exit)
159           think();
160   }
161 }
162
163
164 // MainThread::join() waits for main thread to finish thinking
165
166 void MainThread::join() {
167
168   std::unique_lock<Mutex> lk(mutex);
169   sleepCondition.wait(lk, [&]{ return !thinking; });
170 }
171
172
173 // ThreadPool::init() is called at startup to create and launch requested threads,
174 // that will go immediately to sleep. We cannot use a c'tor because Threads is a
175 // static object and we need a fully initialized engine at this point due to
176 // allocation of Endgames in Thread c'tor.
177
178 void ThreadPool::init() {
179
180   timer = new_thread<TimerThread>();
181   push_back(new_thread<MainThread>());
182   read_uci_options();
183 }
184
185
186 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
187 // done in d'tor because threads must be terminated before freeing us.
188
189 void ThreadPool::exit() {
190
191   delete_thread(timer); // As first because check_time() accesses threads data
192   timer = nullptr;
193
194   for (Thread* th : *this)
195       delete_thread(th);
196
197   clear(); // Get rid of stale pointers
198 }
199
200
201 // ThreadPool::read_uci_options() updates internal threads parameters from the
202 // corresponding UCI options and creates/destroys threads to match the requested
203 // number. Thread objects are dynamically allocated to avoid creating all possible
204 // threads in advance (which include pawns and material tables), even if only a
205 // few are to be used.
206
207 void ThreadPool::read_uci_options() {
208
209   size_t requested  = Options["Threads"];
210
211   assert(requested > 0);
212
213   while (size() < requested)
214       push_back(new_thread<Thread>());
215
216   while (size() > requested)
217   {
218       delete_thread(back());
219       pop_back();
220   }
221 }
222
223
224 // ThreadPool::nodes_searched() returns the number of nodes searched
225
226 int64_t ThreadPool::nodes_searched() {
227
228   int64_t nodes = 0;
229   for (Thread *th : *this)
230       nodes += th->rootPos.nodes_searched();
231   return nodes;
232 }
233
234
235 // ThreadPool::start_thinking() wakes up the main thread sleeping in
236 // MainThread::idle_loop() and starts a new search, then returns immediately.
237
238 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
239                                 StateStackPtr& states) {
240   main()->join();
241
242   Signals.stopOnPonderhit = Signals.firstRootMove = false;
243   Signals.stop = Signals.failedLowAtRoot = false;
244
245   main()->rootMoves.clear();
246   main()->rootPos = pos;
247   Limits = limits;
248   if (states.get()) // If we don't set a new position, preserve current state
249   {
250       SetupStates = std::move(states); // Ownership transfer here
251       assert(!states.get());
252   }
253
254   for (const auto& m : MoveList<LEGAL>(pos))
255       if (   limits.searchmoves.empty()
256           || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
257           main()->rootMoves.push_back(RootMove(m));
258
259   main()->thinking = true;
260   main()->notify_one(); // Wake up main thread: 'thinking' must be already set
261 }