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
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.
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.
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/>.
20 #include <algorithm> // For std::count
28 using namespace Search;
30 ThreadPool Threads; // Global object
32 extern void check_time();
36 // Helpers to launch a thread after creation and joining before delete. Outside the
37 // Thread constructor and destructor because the object must be fully initialized
38 // when start_routine (and hence virtual idle_loop) is called and when joining.
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
46 void delete_thread(ThreadBase* th) {
49 th->exit = true; // Search must be already finished
53 th->join(); // Wait for thread termination
60 // ThreadBase::notify_one() wakes up the thread when there is some work to do
62 void ThreadBase::notify_one() {
64 std::unique_lock<Mutex> lk(mutex);
65 sleepCondition.notify_one();
69 // ThreadBase::wait() set the thread to sleep until 'condition' turns true
71 void ThreadBase::wait(std::atomic<bool>& condition) {
73 std::unique_lock<Mutex> lk(mutex);
74 sleepCondition.wait(lk, [&]{ return bool(condition); });
78 // ThreadBase::wait_while() set the thread to sleep until 'condition' turns false
79 void ThreadBase::wait_while(std::atomic<bool>& condition) {
81 std::unique_lock<Mutex> lk(mutex);
82 sleepCondition.wait(lk, [&]{ return !condition; });
86 // Thread constructor makes some init but does not launch any execution thread,
87 // which will be started only when the constructor returns.
95 idx = Threads.size(); // Starts from 0
99 // TimerThread::idle_loop() is where the timer thread waits Resolution milliseconds
100 // and then calls check_time(). When not searching, thread sleeps until it's woken up.
102 void TimerThread::idle_loop() {
106 std::unique_lock<Mutex> lk(mutex);
109 sleepCondition.wait_for(lk, std::chrono::milliseconds(run ? Resolution : INT_MAX));
119 // Thread::idle_loop() is where the thread is parked when it has no work to do
121 void Thread::idle_loop() {
125 std::unique_lock<Mutex> lk(mutex);
127 while (!searching && !exit)
128 sleepCondition.wait(lk);
132 if (!exit && searching)
138 // MainThread::idle_loop() is where the main thread is parked waiting to be started
139 // when there is a new search. The main thread will launch all the slave threads.
141 void MainThread::idle_loop() {
145 std::unique_lock<Mutex> lk(mutex);
149 while (!thinking && !exit)
151 sleepCondition.notify_one(); // Wake up the UI thread if needed
152 sleepCondition.wait(lk);
163 // MainThread::join() waits for main thread to finish thinking
165 void MainThread::join() {
167 std::unique_lock<Mutex> lk(mutex);
168 sleepCondition.wait(lk, [&]{ return !thinking; });
172 // ThreadPool::init() is called at startup to create and launch requested threads,
173 // that will go immediately to sleep. We cannot use a constructor because Threads
174 // is a static object and we need a fully initialized engine at this point due to
175 // allocation of Endgames in the Thread constructor.
177 void ThreadPool::init() {
179 timer = new_thread<TimerThread>();
180 push_back(new_thread<MainThread>());
185 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
186 // done in destructor because threads must be terminated before freeing us.
188 void ThreadPool::exit() {
190 delete_thread(timer); // As first because check_time() accesses threads data
193 for (Thread* th : *this)
196 clear(); // Get rid of stale pointers
200 // ThreadPool::read_uci_options() updates internal threads parameters from the
201 // corresponding UCI options and creates/destroys threads to match the requested
202 // number. Thread objects are dynamically allocated to avoid creating all possible
203 // threads in advance (which include pawns and material tables), even if only a
204 // few are to be used.
206 void ThreadPool::read_uci_options() {
208 size_t requested = Options["Threads"];
210 assert(requested > 0);
212 while (size() < requested)
213 push_back(new_thread<Thread>());
215 while (size() > requested)
217 delete_thread(back());
223 // ThreadPool::nodes_searched() returns the number of nodes searched
225 int64_t ThreadPool::nodes_searched() {
228 for (Thread *th : *this)
229 nodes += th->rootPos.nodes_searched();
234 // ThreadPool::start_thinking() wakes up the main thread sleeping in
235 // MainThread::idle_loop() and starts a new search, then returns immediately.
237 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
238 StateStackPtr& states) {
241 Signals.stopOnPonderhit = Signals.firstRootMove = false;
242 Signals.stop = Signals.failedLowAtRoot = false;
244 main()->rootMoves.clear();
245 main()->rootPos = pos;
247 if (states.get()) // If we don't set a new position, preserve current state
249 SetupStates = std::move(states); // Ownership transfer here
250 assert(!states.get());
253 for (const auto& m : MoveList<LEGAL>(pos))
254 if ( limits.searchmoves.empty()
255 || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
256 main()->rootMoves.push_back(RootMove(m));
258 main()->thinking = true;
259 main()->notify_one(); // Wake up main thread: 'thinking' must be already set