]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Improve multi-threaded mate finding
[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   Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm> // For std::count
22 #include <cassert>
23
24 #include "movegen.h"
25 #include "search.h"
26 #include "thread.h"
27 #include "syzygy/tbprobe.h"
28
29 ThreadPool Threads; // Global object
30
31
32 /// Thread constructor launches the thread and waits until it goes to sleep
33 /// in idle_loop(). Note that 'searching' and 'exit' should be alredy set.
34
35 Thread::Thread(size_t n) : idx(n), stdThread(&Thread::idle_loop, this) {
36
37   wait_for_search_finished();
38 }
39
40
41 /// Thread destructor wakes up the thread in idle_loop() and waits
42 /// for its termination. Thread should be already waiting.
43
44 Thread::~Thread() {
45
46   assert(!searching);
47
48   exit = true;
49   start_searching();
50   stdThread.join();
51 }
52
53
54 /// Thread::start_searching() wakes up the thread that will start the search
55
56 void Thread::start_searching() {
57
58   std::lock_guard<Mutex> lk(mutex);
59   searching = true;
60   cv.notify_one(); // Wake up the thread in idle_loop()
61 }
62
63
64 /// Thread::wait_for_search_finished() blocks on the condition variable
65 /// until the thread has finished searching.
66
67 void Thread::wait_for_search_finished() {
68
69   std::unique_lock<Mutex> lk(mutex);
70   cv.wait(lk, [&]{ return !searching; });
71 }
72
73
74 /// Thread::idle_loop() is where the thread is parked, blocked on the
75 /// condition variable, when it has no work to do.
76
77 void Thread::idle_loop() {
78
79   WinProcGroup::bindThisThread(idx);
80
81   while (true)
82   {
83       std::unique_lock<Mutex> lk(mutex);
84       searching = false;
85       cv.notify_one(); // Wake up anyone waiting for search finished
86       cv.wait(lk, [&]{ return searching; });
87
88       if (exit)
89           return;
90
91       lk.unlock();
92
93       search();
94   }
95 }
96
97
98 /// ThreadPool::init() creates and launches the threads that will go
99 /// immediately to sleep in idle_loop. We cannot use the c'tor because
100 /// Threads is a static object and we need a fully initialized engine at
101 /// this point due to allocation of Endgames in the Thread constructor.
102
103 void ThreadPool::init(size_t requested) {
104
105   push_back(new MainThread(0));
106   set(requested);
107 }
108
109
110 /// ThreadPool::exit() terminates threads before the program exits. Cannot be
111 /// done in the destructor because threads must be terminated before deleting
112 /// any static object, so before main() returns.
113
114 void ThreadPool::exit() {
115
116   main()->wait_for_search_finished();
117   set(0);
118 }
119
120
121 /// ThreadPool::set() creates/destroys threads to match the requested number
122
123 void ThreadPool::set(size_t requested) {
124
125   while (size() < requested)
126       push_back(new Thread(size()));
127
128   while (size() > requested)
129       delete back(), pop_back();
130 }
131
132
133 /// ThreadPool::start_thinking() wakes up main thread waiting in idle_loop() and
134 /// returns immediately. Main thread will wake up other threads and start the search.
135
136 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
137                                 const Search::LimitsType& limits, bool ponderMode) {
138
139   main()->wait_for_search_finished();
140
141   stopOnPonderhit = stop = false;
142   ponder = ponderMode;
143   Search::Limits = limits;
144   Search::RootMoves rootMoves;
145
146   for (const auto& m : MoveList<LEGAL>(pos))
147       if (   limits.searchmoves.empty()
148           || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
149           rootMoves.emplace_back(m);
150
151   if (!rootMoves.empty())
152       Tablebases::filter_root_moves(pos, rootMoves);
153
154   // After ownership transfer 'states' becomes empty, so if we stop the search
155   // and call 'go' again without setting a new position states.get() == NULL.
156   assert(states.get() || setupStates.get());
157
158   if (states.get())
159       setupStates = std::move(states); // Ownership transfer, states is now empty
160
161   // We use Position::set() to set root position across threads. But there are
162   // some StateInfo fields (previous, pliesFromNull, capturedPiece) that cannot
163   // be deduced from a fen string, so set() clears them and to not lose the info
164   // we need to backup and later restore setupStates->back(). Note that setupStates
165   // is shared by threads but is accessed in read-only mode.
166   StateInfo tmp = setupStates->back();
167
168   for (Thread* th : Threads)
169   {
170       th->nodes = th->tbHits = 0;
171       th->rootDepth = th->completedDepth = DEPTH_ZERO;
172       th->rootMoves = rootMoves;
173       th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th);
174   }
175
176   setupStates->back() = tmp;
177
178   main()->start_searching();
179 }