]> git.sesse.net Git - stockfish/blob - src/thread.cpp
002819de566ce71a2c91e2566ca481bf1376445c
[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-2010 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 <iostream>
21
22 #include "thread.h"
23 #include "ucioption.h"
24
25 ThreadsManager ThreadsMgr; // Global object definition
26
27 namespace {
28
29  // init_thread() is the function which is called when a new thread is
30  // launched. It simply calls the idle_loop() function with the supplied
31  // threadID. There are two versions of this function; one for POSIX
32  // threads and one for Windows threads.
33
34 #if !defined(_MSC_VER)
35
36   void* init_thread(void* threadID) {
37
38     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
39     return NULL;
40   }
41
42 #else
43
44   DWORD WINAPI init_thread(LPVOID threadID) {
45
46     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
47     return 0;
48   }
49
50 #endif
51
52 }
53
54
55 // read_uci_options() updates number of active threads and other internal
56 // parameters according to the UCI options values. It is called before
57 // to start a new search.
58
59 void ThreadsManager::read_uci_options() {
60
61   maxThreadsPerSplitPoint = Options["Maximum Number of Threads per Split Point"].value<int>();
62   minimumSplitDepth       = Options["Minimum Split Depth"].value<int>() * ONE_PLY;
63   useSleepingThreads      = Options["Use Sleeping Threads"].value<bool>();
64   activeThreads           = Options["Threads"].value<int>();
65 }
66
67
68 // init_threads() is called during startup. Initializes locks and condition
69 // variables and launches all threads sending them immediately to sleep.
70
71 void ThreadsManager::init_threads() {
72
73   int arg[MAX_THREADS];
74
75   // This flag is needed to properly end the threads when program exits
76   allThreadsShouldExit = false;
77
78   // Threads will sent to sleep as soon as created, only main thread is kept alive
79   activeThreads = 1;
80   threads[0].state = THREAD_SEARCHING;
81
82   // Allocate pawn and material hash tables for main thread
83   init_hash_tables();
84
85   lock_init(&mpLock);
86
87   // Initialize thread and split point locks
88   for (int i = 0; i < MAX_THREADS; i++)
89   {
90       lock_init(&threads[i].sleepLock);
91       cond_init(&threads[i].sleepCond);
92
93       for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
94           lock_init(&(threads[i].splitPoints[j].lock));
95   }
96
97   // Create and startup all the threads but the main that is already running
98   for (int i = 1; i < MAX_THREADS; i++)
99   {
100       threads[i].state = THREAD_INITIALIZING;
101       arg[i] = i;
102
103 #if !defined(_MSC_VER)
104       pthread_t pthread[1];
105       bool ok = (pthread_create(pthread, NULL, init_thread, (void*)(&arg[i])) == 0);
106       pthread_detach(pthread[0]);
107 #else
108       bool ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&arg[i]), 0, NULL) != NULL);
109 #endif
110       if (!ok)
111       {
112           std::cout << "Failed to create thread number " << i << std::endl;
113           exit(EXIT_FAILURE);
114       }
115
116       // Wait until the thread has finished launching and is gone to sleep
117       while (threads[i].state == THREAD_INITIALIZING) {}
118   }
119 }
120
121
122 // exit_threads() is called when the program exits. It makes all the
123 // helper threads exit cleanly.
124
125 void ThreadsManager::exit_threads() {
126
127   // Force the woken up threads to exit idle_loop() and hence terminate
128   allThreadsShouldExit = true;
129
130   for (int i = 0; i < MAX_THREADS; i++)
131   {
132       // Wake up all the threads and waits for termination
133       if (i != 0)
134       {
135           threads[i].wake_up();
136           while (threads[i].state != THREAD_TERMINATED) {}
137       }
138
139       // Now we can safely destroy the locks and wait conditions
140       lock_destroy(&threads[i].sleepLock);
141       cond_destroy(&threads[i].sleepCond);
142
143       for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
144           lock_destroy(&(threads[i].splitPoints[j].lock));
145   }
146
147   lock_destroy(&mpLock);
148 }
149
150
151 // init_hash_tables() dynamically allocates pawn and material hash tables
152 // according to the number of active threads. This avoids preallocating
153 // memory for all possible threads if only few are used as, for instance,
154 // on mobile devices where memory is scarce and allocating for MAX_THREADS
155 // threads could even result in a crash.
156
157 void ThreadsManager::init_hash_tables() {
158
159   for (int i = 0; i < activeThreads; i++)
160   {
161       threads[i].pawnTable.init();
162       threads[i].materialTable.init();
163   }
164 }
165
166
167 // cutoff_at_splitpoint() checks whether a beta cutoff has occurred in
168 // the thread's currently active split point, or in some ancestor of
169 // the current split point.
170
171 bool ThreadsManager::cutoff_at_splitpoint(int threadID) const {
172
173   assert(threadID >= 0 && threadID < activeThreads);
174
175   SplitPoint* sp = threads[threadID].splitPoint;
176
177   for ( ; sp && !sp->betaCutoff; sp = sp->parent) {}
178   return sp != NULL;
179 }
180
181
182 // thread_is_available() checks whether the thread with threadID "slave" is
183 // available to help the thread with threadID "master" at a split point. An
184 // obvious requirement is that "slave" must be idle. With more than two
185 // threads, this is not by itself sufficient:  If "slave" is the master of
186 // some active split point, it is only available as a slave to the other
187 // threads which are busy searching the split point at the top of "slave"'s
188 // split point stack (the "helpful master concept" in YBWC terminology).
189
190 bool ThreadsManager::thread_is_available(int slave, int master) const {
191
192   assert(slave >= 0 && slave < activeThreads);
193   assert(master >= 0 && master < activeThreads);
194   assert(activeThreads > 1);
195
196   if (threads[slave].state != THREAD_AVAILABLE || slave == master)
197       return false;
198
199   // Make a local copy to be sure doesn't change under our feet
200   int localActiveSplitPoints = threads[slave].activeSplitPoints;
201
202   // No active split points means that the thread is available as
203   // a slave for any other thread.
204   if (localActiveSplitPoints == 0 || activeThreads == 2)
205       return true;
206
207   // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
208   // that is known to be > 0, instead of threads[slave].activeSplitPoints that
209   // could have been set to 0 by another thread leading to an out of bound access.
210   if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
211       return true;
212
213   return false;
214 }
215
216
217 // available_thread_exists() tries to find an idle thread which is available as
218 // a slave for the thread with threadID "master".
219
220 bool ThreadsManager::available_thread_exists(int master) const {
221
222   assert(master >= 0 && master < activeThreads);
223   assert(activeThreads > 1);
224
225   for (int i = 0; i < activeThreads; i++)
226       if (thread_is_available(i, master))
227           return true;
228
229   return false;
230 }
231
232
233 // split() does the actual work of distributing the work at a node between
234 // several available threads. If it does not succeed in splitting the
235 // node (because no idle threads are available, or because we have no unused
236 // split point objects), the function immediately returns. If splitting is
237 // possible, a SplitPoint object is initialized with all the data that must be
238 // copied to the helper threads and we tell our helper threads that they have
239 // been assigned work. This will cause them to instantly leave their idle loops and
240 // call search().When all threads have returned from search() then split() returns.
241
242 template <bool Fake>
243 void ThreadsManager::split(Position& pos, SearchStack* ss, Value* alpha, const Value beta,
244                            Value* bestValue, Depth depth, Move threatMove,
245                            int moveCount, MovePicker* mp, bool pvNode) {
246   assert(pos.is_ok());
247   assert(*bestValue >= -VALUE_INFINITE);
248   assert(*bestValue <= *alpha);
249   assert(*alpha < beta);
250   assert(beta <= VALUE_INFINITE);
251   assert(depth > DEPTH_ZERO);
252   assert(pos.thread() >= 0 && pos.thread() < activeThreads);
253   assert(activeThreads > 1);
254
255   int i, master = pos.thread();
256   Thread& masterThread = threads[master];
257
258   lock_grab(&mpLock);
259
260   // If no other thread is available to help us, or if we have too many
261   // active split points, don't split.
262   if (   !available_thread_exists(master)
263       || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
264   {
265       lock_release(&mpLock);
266       return;
267   }
268
269   // Pick the next available split point object from the split point stack
270   SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
271
272   // Initialize the split point object
273   splitPoint.parent = masterThread.splitPoint;
274   splitPoint.master = master;
275   splitPoint.betaCutoff = false;
276   splitPoint.depth = depth;
277   splitPoint.threatMove = threatMove;
278   splitPoint.alpha = *alpha;
279   splitPoint.beta = beta;
280   splitPoint.pvNode = pvNode;
281   splitPoint.bestValue = *bestValue;
282   splitPoint.mp = mp;
283   splitPoint.moveCount = moveCount;
284   splitPoint.pos = &pos;
285   splitPoint.nodes = 0;
286   splitPoint.ss = ss;
287   for (i = 0; i < activeThreads; i++)
288       splitPoint.slaves[i] = 0;
289
290   masterThread.splitPoint = &splitPoint;
291
292   // If we are here it means we are not available
293   assert(masterThread.state != THREAD_AVAILABLE);
294
295   int workersCnt = 1; // At least the master is included
296
297   // Allocate available threads setting state to THREAD_BOOKED
298   for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
299       if (thread_is_available(i, master))
300       {
301           threads[i].state = THREAD_BOOKED;
302           threads[i].splitPoint = &splitPoint;
303           splitPoint.slaves[i] = 1;
304           workersCnt++;
305       }
306
307   assert(Fake || workersCnt > 1);
308
309   // We can release the lock because slave threads are already booked and master is not available
310   lock_release(&mpLock);
311
312   // Tell the threads that they have work to do. This will make them leave
313   // their idle loop.
314   for (i = 0; i < activeThreads; i++)
315       if (i == master || splitPoint.slaves[i])
316       {
317           assert(i == master || threads[i].state == THREAD_BOOKED);
318
319           threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
320
321           if (useSleepingThreads && i != master)
322               threads[i].wake_up();
323       }
324
325   // Everything is set up. The master thread enters the idle loop, from
326   // which it will instantly launch a search, because its state is
327   // THREAD_WORKISWAITING.  We send the split point as a second parameter to the
328   // idle loop, which means that the main thread will return from the idle
329   // loop when all threads have finished their work at this split point.
330   idle_loop(master, &splitPoint);
331
332   // We have returned from the idle loop, which means that all threads are
333   // finished. Update alpha and bestValue, and return.
334   lock_grab(&mpLock);
335
336   *alpha = splitPoint.alpha;
337   *bestValue = splitPoint.bestValue;
338   masterThread.activeSplitPoints--;
339   masterThread.splitPoint = splitPoint.parent;
340   pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);
341
342   lock_release(&mpLock);
343 }
344
345 // Explicit template instantiations
346 template void ThreadsManager::split<0>(Position&, SearchStack*, Value*, const Value, Value*, Depth, Move, int, MovePicker*, bool);
347 template void ThreadsManager::split<1>(Position&, SearchStack*, Value*, const Value, Value*, Depth, Move, int, MovePicker*, bool);