]> git.sesse.net Git - stockfish/blob - src/thread.cpp
Retire States global variable
[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 "uci.h"
28 #include "syzygy/tbprobe.h"
29
30 ThreadPool Threads; // Global object
31
32 /// Thread constructor launches the thread and then waits until it goes to sleep
33 /// in idle_loop().
34
35 Thread::Thread() {
36
37   exit = false;
38   selDepth = 0;
39   nodes = tbHits = 0;
40   idx = Threads.size(); // Start from 0
41
42   std::unique_lock<Mutex> lk(mutex);
43   searching = true;
44   nativeThread = std::thread(&Thread::idle_loop, this);
45   sleepCondition.wait(lk, [&]{ return !searching; });
46 }
47
48
49 /// Thread destructor waits for thread termination before returning
50
51 Thread::~Thread() {
52
53   mutex.lock();
54   exit = true;
55   sleepCondition.notify_one();
56   mutex.unlock();
57   nativeThread.join();
58 }
59
60
61 /// Thread::wait_for_search_finished() waits on sleep condition
62 /// until not searching
63
64 void Thread::wait_for_search_finished() {
65
66   std::unique_lock<Mutex> lk(mutex);
67   sleepCondition.wait(lk, [&]{ return !searching; });
68 }
69
70
71 /// Thread::start_searching() wakes up the thread that will start the search
72
73 void Thread::start_searching() {
74
75   std::unique_lock<Mutex> lk(mutex);
76   searching = true;
77   sleepCondition.notify_one();
78 }
79
80
81 /// Thread::idle_loop() is where the thread is parked when it has no work to do
82
83 void Thread::idle_loop() {
84
85   WinProcGroup::bindThisThread(idx);
86
87   while (!exit)
88   {
89       std::unique_lock<Mutex> lk(mutex);
90
91       searching = false;
92
93       while (!searching && !exit)
94       {
95           sleepCondition.notify_one(); // Wake up any waiting thread
96           sleepCondition.wait(lk);
97       }
98
99       lk.unlock();
100
101       if (!exit)
102           search();
103   }
104 }
105
106
107 /// ThreadPool::init() creates and launches requested threads that will go
108 /// immediately to sleep. We cannot use a constructor because Threads is a
109 /// static object and we need a fully initialized engine at this point due to
110 /// allocation of Endgames in the Thread constructor.
111
112 void ThreadPool::init() {
113
114   push_back(new MainThread());
115   read_uci_options();
116 }
117
118
119 /// ThreadPool::exit() terminates threads before the program exits. Cannot be
120 /// done in destructor because threads must be terminated before deleting any
121 /// static objects while still in main().
122
123 void ThreadPool::exit() {
124
125   while (size())
126       delete back(), pop_back();
127 }
128
129
130 /// ThreadPool::read_uci_options() updates internal threads parameters from the
131 /// corresponding UCI options and creates/destroys threads to match requested
132 /// number. Thread objects are dynamically allocated.
133
134 void ThreadPool::read_uci_options() {
135
136   size_t requested = Options["Threads"];
137
138   assert(requested > 0);
139
140   while (size() < requested)
141       push_back(new Thread());
142
143   while (size() > requested)
144       delete back(), pop_back();
145 }
146
147
148 /// ThreadPool::nodes_searched() returns the number of nodes searched
149
150 uint64_t ThreadPool::nodes_searched() const {
151
152   uint64_t nodes = 0;
153   for (Thread* th : *this)
154       nodes += th->nodes.load(std::memory_order_relaxed);
155   return nodes;
156 }
157
158
159 /// ThreadPool::tb_hits() returns the number of TB hits
160
161 uint64_t ThreadPool::tb_hits() const {
162
163   uint64_t hits = 0;
164   for (Thread* th : *this)
165       hits += th->tbHits.load(std::memory_order_relaxed);
166   return hits;
167 }
168
169
170 /// ThreadPool::start_thinking() wakes up the main thread sleeping in idle_loop()
171 /// and starts a new search, then returns immediately.
172
173 void ThreadPool::start_thinking(Position& pos, StateListPtr& states,
174                                 const Search::LimitsType& limits, bool ponderMode) {
175
176   main()->wait_for_search_finished();
177
178   stopOnPonderhit = stop = false;
179   ponder = ponderMode;
180   Search::Limits = limits;
181   Search::RootMoves rootMoves;
182
183   for (const auto& m : MoveList<LEGAL>(pos))
184       if (   limits.searchmoves.empty()
185           || std::count(limits.searchmoves.begin(), limits.searchmoves.end(), m))
186           rootMoves.push_back(Search::RootMove(m));
187
188   if (!rootMoves.empty())
189       Tablebases::filter_root_moves(pos, rootMoves);
190
191   // After ownership transfer 'states' becomes empty, so if we stop the search
192   // and call 'go' again without setting a new position states.get() == NULL.
193   assert(states.get() || setupStates.get());
194
195   if (states.get())
196       setupStates = std::move(states); // Ownership transfer, states is now empty
197
198   StateInfo tmp = setupStates->back();
199
200   for (Thread* th : Threads)
201   {
202       th->nodes = 0;
203       th->tbHits = 0;
204       th->rootDepth = DEPTH_ZERO;
205       th->rootMoves = rootMoves;
206       th->rootPos.set(pos.fen(), pos.is_chess960(), &setupStates->back(), th);
207   }
208
209   setupStates->back() = tmp; // Restore st->previous, cleared by Position::set()
210
211   main()->start_searching();
212 }