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