]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Simplify threats
[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   idx = Threads.size(); // Starts from 0
95 }
96
97
98 // TimerThread::idle_loop() is where the timer thread waits Resolution milliseconds
99 // and then calls check_time(). When not searching, thread sleeps until it's woken up.
100
101 void TimerThread::idle_loop() {
102
103   while (!exit)
104   {
105       std::unique_lock<Mutex> lk(mutex);
106
107       if (!exit)
108           sleepCondition.wait_for(lk, std::chrono::milliseconds(run ? Resolution : INT_MAX));
109
110       lk.unlock();
111
112       if (!exit && run)
113           check_time();
114   }
115 }
116
117
118 // Thread::idle_loop() is where the thread is parked when it has no work to do
119
120 void Thread::idle_loop() {
121
122   while (!exit)
123   {
124       std::unique_lock<Mutex> lk(mutex);
125
126       while (!searching && !exit)
127           sleepCondition.wait(lk);
128
129       lk.unlock();
130
131       if (!exit && searching)
132           search();
133   }
134 }
135
136
137 // MainThread::idle_loop() is where the main thread is parked waiting to be started
138 // when there is a new search. The main thread will launch all the slave threads.
139
140 void MainThread::idle_loop() {
141
142   while (!exit)
143   {
144       std::unique_lock<Mutex> lk(mutex);
145
146       thinking = false;
147
148       while (!thinking && !exit)
149       {
150           sleepCondition.notify_one(); // Wake up the UI thread if needed
151           sleepCondition.wait(lk);
152       }
153
154       lk.unlock();
155
156       if (!exit)
157           think();
158   }
159 }
160
161
162 // MainThread::join() waits for main thread to finish thinking
163
164 void MainThread::join() {
165
166   std::unique_lock<Mutex> lk(mutex);
167   sleepCondition.wait(lk, [&]{ return !thinking; });
168 }
169
170
171 // ThreadPool::init() is called at startup to create and launch requested threads,
172 // that will go immediately to sleep. We cannot use a c'tor because Threads is a
173 // static object and we need a fully initialized engine at this point due to
174 // allocation of Endgames in Thread c'tor.
175
176 void ThreadPool::init() {
177
178   timer = new_thread<TimerThread>();
179   push_back(new_thread<MainThread>());
180   read_uci_options();
181 }
182
183
184 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
185 // done in d'tor because threads must be terminated before freeing us.
186
187 void ThreadPool::exit() {
188
189   delete_thread(timer); // As first because check_time() accesses threads data
190   timer = nullptr;
191
192   for (Thread* th : *this)
193       delete_thread(th);
194
195   clear(); // Get rid of stale pointers
196 }
197
198
199 // ThreadPool::read_uci_options() updates internal threads parameters from the
200 // corresponding UCI options and creates/destroys threads to match the requested
201 // number. Thread objects are dynamically allocated to avoid creating all possible
202 // threads in advance (which include pawns and material tables), even if only a
203 // few are to be used.
204
205 void ThreadPool::read_uci_options() {
206
207   size_t requested  = Options["Threads"];
208
209   assert(requested > 0);
210
211   while (size() < requested)
212       push_back(new_thread<Thread>());
213
214   while (size() > requested)
215   {
216       delete_thread(back());
217       pop_back();
218   }
219 }
220
221
222 // ThreadPool::nodes_searched() returns the number of nodes searched
223
224 int64_t ThreadPool::nodes_searched() {
225
226   int64_t nodes = 0;
227   for (Thread *th : *this)
228       nodes += th->rootPos.nodes_searched();
229   return nodes;
230 }
231
232
233 // ThreadPool::start_thinking() wakes up the main thread sleeping in
234 // MainThread::idle_loop() and starts a new search, then returns immediately.
235
236 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
237                                 StateStackPtr& states) {
238   main()->join();
239
240   Signals.stopOnPonderhit = Signals.firstRootMove = false;
241   Signals.stop = Signals.failedLowAtRoot = false;
242
243   main()->rootMoves.clear();
244   main()->rootPos = pos;
245   Limits = limits;
246   if (states.get()) // If we don't set a new position, preserve current state
247   {
248       SetupStates = std::move(states); // Ownership transfer here
249       assert(!states.get());
250   }
251
252   for (const auto& m : MoveList<LEGAL>(pos))
253       if (   limits.searchmoves.empty()
254           || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
255           main()->rootMoves.push_back(RootMove(m));
256
257   main()->thinking = true;
258   main()->notify_one(); // Wake up main thread: 'thinking' must be already set
259 }