]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Use atomics instead of volatile
[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(std::atomic<bool>& condition) {
72
73   std::unique_lock<Mutex> lk(mutex);
74   sleepCondition.wait(lk, [&]{ return bool(condition); });
75 }
76
77
78 // ThreadBase::wait_while() set the thread to sleep until 'condition' turns false
79 void ThreadBase::wait_while(std::atomic<bool>& condition) {
80
81   std::unique_lock<Mutex> lk(mutex);
82   sleepCondition.wait(lk, [&]{ return !condition; });
83 }
84
85
86 // Thread c'tor makes some init but does not launch any execution thread that
87 // will be started only when c'tor returns.
88
89 Thread::Thread() {
90
91   searching = false;
92   maxPly = 0;
93   history.clear();
94   counterMoves.clear();
95   idx = Threads.size(); // Starts from 0
96 }
97
98
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.
101
102 void TimerThread::idle_loop() {
103
104   while (!exit)
105   {
106       std::unique_lock<Mutex> lk(mutex);
107
108       if (!exit)
109           sleepCondition.wait_for(lk, std::chrono::milliseconds(run ? Resolution : INT_MAX));
110
111       lk.unlock();
112
113       if (!exit && run)
114           check_time();
115   }
116 }
117
118
119 // Thread::idle_loop() is where the thread is parked when it has no work to do
120
121 void Thread::idle_loop() {
122
123   while (!exit)
124   {
125       std::unique_lock<Mutex> lk(mutex);
126
127       while (!searching && !exit)
128           sleepCondition.wait(lk);
129
130       lk.unlock();
131
132       if (!exit && searching)
133           search();
134   }
135 }
136
137
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.
140
141 void MainThread::idle_loop() {
142
143   while (!exit)
144   {
145       std::unique_lock<Mutex> lk(mutex);
146
147       thinking = false;
148
149       while (!thinking && !exit)
150       {
151           sleepCondition.notify_one(); // Wake up the UI thread if needed
152           sleepCondition.wait(lk);
153       }
154
155       lk.unlock();
156
157       if (!exit)
158           think();
159   }
160 }
161
162
163 // MainThread::join() waits for main thread to finish thinking
164
165 void MainThread::join() {
166
167   std::unique_lock<Mutex> lk(mutex);
168   sleepCondition.wait(lk, [&]{ return !thinking; });
169 }
170
171
172 // ThreadPool::init() is called at startup to create and launch requested threads,
173 // that will go immediately to sleep. We cannot use a c'tor because Threads is a
174 // static object and we need a fully initialized engine at this point due to
175 // allocation of Endgames in Thread c'tor.
176
177 void ThreadPool::init() {
178
179   timer = new_thread<TimerThread>();
180   push_back(new_thread<MainThread>());
181   read_uci_options();
182 }
183
184
185 // ThreadPool::exit() terminates the threads before the program exits. Cannot be
186 // done in d'tor because threads must be terminated before freeing us.
187
188 void ThreadPool::exit() {
189
190   delete_thread(timer); // As first because check_time() accesses threads data
191   timer = nullptr;
192
193   for (Thread* th : *this)
194       delete_thread(th);
195
196   clear(); // Get rid of stale pointers
197 }
198
199
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.
205
206 void ThreadPool::read_uci_options() {
207
208   size_t requested  = Options["Threads"];
209
210   assert(requested > 0);
211
212   while (size() < requested)
213       push_back(new_thread<Thread>());
214
215   while (size() > requested)
216   {
217       delete_thread(back());
218       pop_back();
219   }
220 }
221
222
223 // ThreadPool::nodes_searched() returns the number of nodes searched
224
225 int64_t ThreadPool::nodes_searched() {
226
227   int64_t nodes = 0;
228   for (Thread *th : *this)
229       nodes += th->rootPos.nodes_searched();
230   return nodes;
231 }
232
233
234 // ThreadPool::start_thinking() wakes up the main thread sleeping in
235 // MainThread::idle_loop() and starts a new search, then returns immediately.
236
237 void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
238                                 StateStackPtr& states) {
239   main()->join();
240
241   Signals.stopOnPonderhit = Signals.firstRootMove = false;
242   Signals.stop = Signals.failedLowAtRoot = false;
243
244   main()->rootMoves.clear();
245   main()->rootPos = pos;
246   Limits = limits;
247   if (states.get()) // If we don't set a new position, preserve current state
248   {
249       SetupStates = std::move(states); // Ownership transfer here
250       assert(!states.get());
251   }
252
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));
257
258   main()->thinking = true;
259   main()->notify_one(); // Wake up main thread: 'thinking' must be already set
260 }