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