]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Introduce struct Mutex and ConditionVariable
[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-2012 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 <cassert>
21 #include <iostream>
22
23 #include "movegen.h"
24 #include "search.h"
25 #include "thread.h"
26 #include "ucioption.h"
27
28 using namespace Search;
29
30 ThreadPool Threads; // Global object
31
32 namespace { extern "C" {
33
34  // start_routine() is the C function which is called when a new thread
35  // is launched. It is a wrapper to member function pointed by start_fn.
36
37  long start_routine(Thread* th) { (th->*(th->start_fn))(); return 0; }
38
39 } }
40
41
42 // Thread c'tor starts a newly-created thread of execution that will call
43 // the idle loop function pointed by start_fn going immediately to sleep.
44
45 Thread::Thread(Fn fn) {
46
47   is_searching = do_exit = false;
48   maxPly = splitPointsCnt = 0;
49   curSplitPoint = NULL;
50   start_fn = fn;
51   idx = Threads.size();
52
53   do_sleep = (fn != &Thread::main_loop); // Avoid a race with start_searching()
54
55   if (!thread_create(handle, start_routine, this))
56   {
57       std::cerr << "Failed to create thread number " << idx << std::endl;
58       ::exit(EXIT_FAILURE);
59   }
60 }
61
62
63 // Thread d'tor waits for thread termination before to return.
64
65 Thread::~Thread() {
66
67   assert(do_sleep);
68
69   do_exit = true; // Search must be already finished
70   wake_up();
71   thread_join(handle); // Wait for thread termination
72 }
73
74
75 // Thread::timer_loop() is where the timer thread waits maxPly milliseconds and
76 // then calls check_time(). If maxPly is 0 thread sleeps until is woken up.
77 extern void check_time();
78
79 void Thread::timer_loop() {
80
81   while (!do_exit)
82   {
83       mutex.lock();
84       sleepCondition.wait_for(mutex, maxPly ? maxPly : INT_MAX);
85       mutex.unlock();
86       check_time();
87   }
88 }
89
90
91 // Thread::main_loop() is where the main thread is parked waiting to be started
92 // when there is a new search. Main thread will launch all the slave threads.
93
94 void Thread::main_loop() {
95
96   while (true)
97   {
98       mutex.lock();
99
100       do_sleep = true; // Always return to sleep after a search
101       is_searching = false;
102
103       while (do_sleep && !do_exit)
104       {
105           Threads.sleepCondition.notify_one(); // Wake up UI thread if needed
106           sleepCondition.wait(mutex);
107       }
108
109       mutex.unlock();
110
111       if (do_exit)
112           return;
113
114       is_searching = true;
115
116       Search::think();
117   }
118 }
119
120
121 // Thread::wake_up() wakes up the thread, normally at the beginning of the search
122 // or, if "sleeping threads" is used at split time.
123
124 void Thread::wake_up() {
125
126   mutex.lock();
127   sleepCondition.notify_one();
128   mutex.unlock();
129 }
130
131
132 // Thread::wait_for_stop_or_ponderhit() is called when the maximum depth is
133 // reached while the program is pondering. The point is to work around a wrinkle
134 // in the UCI protocol: When pondering, the engine is not allowed to give a
135 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command. We simply
136 // wait here until one of these commands (that raise StopRequest) is sent and
137 // then return, after which the bestmove and pondermove will be printed.
138
139 void Thread::wait_for_stop_or_ponderhit() {
140
141   Signals.stopOnPonderhit = true;
142
143   mutex.lock();
144   while (!Signals.stop) sleepCondition.wait(mutex);;
145   mutex.unlock();
146 }
147
148
149 // Thread::cutoff_occurred() checks whether a beta cutoff has occurred in the
150 // current active split point, or in some ancestor of the split point.
151
152 bool Thread::cutoff_occurred() const {
153
154   for (SplitPoint* sp = curSplitPoint; sp; sp = sp->parent)
155       if (sp->cutoff)
156           return true;
157
158   return false;
159 }
160
161
162 // Thread::is_available_to() checks whether the thread is available to help the
163 // thread 'master' at a split point. An obvious requirement is that thread must
164 // be idle. With more than two threads, this is not sufficient: If the thread is
165 // the master of some active split point, it is only available as a slave to the
166 // slaves which are busy searching the split point at the top of slaves split
167 // point stack (the "helpful master concept" in YBWC terminology).
168
169 bool Thread::is_available_to(Thread* master) const {
170
171   if (is_searching)
172       return false;
173
174   // Make a local copy to be sure doesn't become zero under our feet while
175   // testing next condition and so leading to an out of bound access.
176   int spCnt = splitPointsCnt;
177
178   // No active split points means that the thread is available as a slave for any
179   // other thread otherwise apply the "helpful master" concept if possible.
180   return !spCnt || (splitPoints[spCnt - 1].slavesMask & (1ULL << master->idx));
181 }
182
183
184 // init() is called at startup. Initializes lock and condition variable and
185 // launches requested threads sending them immediately to sleep. We cannot use
186 // a c'tor becuase Threads is a static object and we need a fully initialized
187 // engine at this point due to allocation of endgames in Thread c'tor.
188
189 void ThreadPool::init() {
190
191   timer = new Thread(&Thread::timer_loop);
192   threads.push_back(new Thread(&Thread::main_loop));
193   read_uci_options();
194 }
195
196
197 // d'tor cleanly terminates the threads when the program exits.
198
199 ThreadPool::~ThreadPool() {
200
201   for (size_t i = 0; i < size(); i++)
202       delete threads[i];
203
204   delete timer;
205 }
206
207
208 // read_uci_options() updates internal threads parameters from the corresponding
209 // UCI options and creates/destroys threads to match the requested number. Thread
210 // objects are dynamically allocated to avoid creating in advance all possible
211 // threads, with included pawns and material tables, if only few are used.
212
213 void ThreadPool::read_uci_options() {
214
215   maxThreadsPerSplitPoint = Options["Max Threads per Split Point"];
216   minimumSplitDepth       = Options["Min Split Depth"] * ONE_PLY;
217   useSleepingThreads      = Options["Use Sleeping Threads"];
218   size_t requested        = Options["Threads"];
219
220   assert(requested > 0);
221
222   while (size() < requested)
223       threads.push_back(new Thread(&Thread::idle_loop));
224
225   while (size() > requested)
226   {
227       delete threads.back();
228       threads.pop_back();
229   }
230 }
231
232
233 // wake_up() is called before a new search to start the threads that are waiting
234 // on the sleep condition and to reset maxPly. When useSleepingThreads is set
235 // threads will be woken up at split time.
236
237 void ThreadPool::wake_up() const {
238
239   for (size_t i = 0; i < size(); i++)
240   {
241       threads[i]->maxPly = 0;
242       threads[i]->do_sleep = false;
243
244       if (!useSleepingThreads)
245           threads[i]->wake_up();
246   }
247 }
248
249
250 // sleep() is called after the search finishes to ask all the threads but the
251 // main one to go waiting on a sleep condition.
252
253 void ThreadPool::sleep() const {
254
255   for (size_t i = 1; i < size(); i++) // Main thread will go to sleep by itself
256       threads[i]->do_sleep = true; // to avoid a race with start_searching()
257 }
258
259
260 // available_slave_exists() tries to find an idle thread which is available as
261 // a slave for the thread 'master'.
262
263 bool ThreadPool::available_slave_exists(Thread* master) const {
264
265   for (size_t i = 0; i < size(); i++)
266       if (threads[i]->is_available_to(master))
267           return true;
268
269   return false;
270 }
271
272
273 // split() does the actual work of distributing the work at a node between
274 // several available threads. If it does not succeed in splitting the node
275 // (because no idle threads are available, or because we have no unused split
276 // point objects), the function immediately returns. If splitting is possible, a
277 // SplitPoint object is initialized with all the data that must be copied to the
278 // helper threads and then helper threads are told that they have been assigned
279 // work. This will cause them to instantly leave their idle loops and call
280 // search(). When all threads have returned from search() then split() returns.
281
282 template <bool Fake>
283 Value ThreadPool::split(Position& pos, Stack* ss, Value alpha, Value beta,
284                         Value bestValue, Move* bestMove, Depth depth,
285                         Move threatMove, int moveCount, MovePicker* mp, int nodeType) {
286
287   assert(pos.pos_is_ok());
288   assert(bestValue > -VALUE_INFINITE);
289   assert(bestValue <= alpha);
290   assert(alpha < beta);
291   assert(beta <= VALUE_INFINITE);
292   assert(depth > DEPTH_ZERO);
293
294   Thread* master = pos.this_thread();
295
296   if (master->splitPointsCnt >= MAX_SPLITPOINTS_PER_THREAD)
297       return bestValue;
298
299   // Pick the next available split point from the split point stack
300   SplitPoint& sp = master->splitPoints[master->splitPointsCnt];
301
302   sp.parent = master->curSplitPoint;
303   sp.master = master;
304   sp.cutoff = false;
305   sp.slavesMask = 1ULL << master->idx;
306   sp.depth = depth;
307   sp.bestMove = *bestMove;
308   sp.threatMove = threatMove;
309   sp.alpha = alpha;
310   sp.beta = beta;
311   sp.nodeType = nodeType;
312   sp.bestValue = bestValue;
313   sp.mp = mp;
314   sp.moveCount = moveCount;
315   sp.pos = &pos;
316   sp.nodes = 0;
317   sp.ss = ss;
318
319   assert(master->is_searching);
320
321   master->curSplitPoint = &sp;
322   int slavesCnt = 0;
323
324   // Try to allocate available threads and ask them to start searching setting
325   // is_searching flag. This must be done under lock protection to avoid concurrent
326   // allocation of the same slave by another master.
327   sp.mutex.lock();
328   mutex.lock();
329
330   for (size_t i = 0; i < size() && !Fake; ++i)
331       if (threads[i]->is_available_to(master))
332       {
333           sp.slavesMask |= 1ULL << i;
334           threads[i]->curSplitPoint = &sp;
335           threads[i]->is_searching = true; // Slave leaves idle_loop()
336
337           if (useSleepingThreads)
338               threads[i]->wake_up();
339
340           if (++slavesCnt + 1 >= maxThreadsPerSplitPoint) // Master is always included
341               break;
342       }
343
344   master->splitPointsCnt++;
345
346   mutex.unlock();
347   sp.mutex.unlock();
348
349   // Everything is set up. The master thread enters the idle loop, from which
350   // it will instantly launch a search, because its is_searching flag is set.
351   // The thread will return from the idle loop when all slaves have finished
352   // their work at this split point.
353   if (slavesCnt || Fake)
354   {
355       master->idle_loop();
356
357       // In helpful master concept a master can help only a sub-tree of its split
358       // point, and because here is all finished is not possible master is booked.
359       assert(!master->is_searching);
360   }
361
362   // We have returned from the idle loop, which means that all threads are
363   // finished. Note that setting is_searching and decreasing splitPointsCnt is
364   // done under lock protection to avoid a race with Thread::is_available_to().
365   sp.mutex.lock(); // To protect sp.nodes
366   mutex.lock();
367
368   master->is_searching = true;
369   master->splitPointsCnt--;
370   master->curSplitPoint = sp.parent;
371   pos.set_nodes_searched(pos.nodes_searched() + sp.nodes);
372   *bestMove = sp.bestMove;
373
374   mutex.unlock();
375   sp.mutex.unlock();
376
377   return sp.bestValue;
378 }
379
380 // Explicit template instantiations
381 template Value ThreadPool::split<false>(Position&, Stack*, Value, Value, Value, Move*, Depth, Move, int, MovePicker*, int);
382 template Value ThreadPool::split<true>(Position&, Stack*, Value, Value, Value, Move*, Depth, Move, int, MovePicker*, int);
383
384
385 // set_timer() is used to set the timer to trigger after msec milliseconds.
386 // If msec is 0 then timer is stopped.
387
388 void ThreadPool::set_timer(int msec) {
389
390   timer->mutex.lock();
391   timer->maxPly = msec;
392   timer->sleepCondition.notify_one(); // Wake up and restart the timer
393   timer->mutex.unlock();
394 }
395
396
397 // wait_for_search_finished() waits for main thread to go to sleep, this means
398 // search is finished. Then returns.
399
400 void ThreadPool::wait_for_search_finished() {
401
402   Thread* t = main_thread();
403   t->mutex.lock();
404   t->sleepCondition.notify_one(); // In case is waiting for stop or ponderhit
405   while (!t->do_sleep) sleepCondition.wait(t->mutex);
406   t->mutex.unlock();
407 }
408
409
410 // start_searching() wakes up the main thread sleeping in  main_loop() so to start
411 // a new search, then returns immediately.
412
413 void ThreadPool::start_searching(const Position& pos, const LimitsType& limits,
414                                  const std::vector<Move>& searchMoves) {
415   wait_for_search_finished();
416
417   SearchTime.restart(); // As early as possible
418
419   Signals.stopOnPonderhit = Signals.firstRootMove = false;
420   Signals.stop = Signals.failedLowAtRoot = false;
421
422   RootPosition = pos;
423   Limits = limits;
424   RootMoves.clear();
425
426   for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
427       if (searchMoves.empty() || count(searchMoves.begin(), searchMoves.end(), ml.move()))
428           RootMoves.push_back(RootMove(ml.move()));
429
430   main_thread()->do_sleep = false;
431   main_thread()->wake_up();
432 }