// when start_routine (and hence virtual idle_loop) is called and when joining.
template<typename T> T* new_thread() {
- T* th = new T();
- th->nativeThread = std::thread(&ThreadBase::idle_loop, th); // Will go to sleep
- return th;
+ std::thread* th = new T;
+ *th = std::thread(&T::idle_loop, (T*)th); // Will go to sleep
+ return (T*)th;
}
void delete_thread(ThreadBase* th) {
th->mutex.unlock();
th->notify_one();
- th->nativeThread.join(); // Wait for thread termination
+ th->join(); // Wait for thread termination
delete th;
}
void ThreadBase::notify_one() {
- std::unique_lock<Mutex>(this->mutex);
+ std::unique_lock<Mutex> lk(mutex);
sleepCondition.notify_one();
}
while (!thinking && !exit)
{
- Threads.sleepCondition.notify_one(); // Wake up the UI thread if needed
+ sleepCondition.notify_one(); // Wake up the UI thread if needed
sleepCondition.wait(lk);
}
}
+// MainThread::join() waits for main thread to finish the search
+
+void MainThread::join() {
+
+ std::unique_lock<Mutex> lk(mutex);
+ sleepCondition.wait(lk, [&]{ return !thinking; });
+}
+
+
// ThreadPool::init() is called at startup to create and launch requested threads,
// that will go immediately to sleep. We cannot use a c'tor because Threads is a
// static object and we need a fully initialized engine at this point due to
void ThreadPool::exit() {
delete_thread(timer); // As first because check_time() accesses threads data
+ timer = nullptr;
for (Thread* th : *this)
delete_thread(th);
+
+ clear(); // Get rid of stale pointers
}
assert(requested > 0);
- // If zero (default) then set best minimum split depth automatically
- if (!minimumSplitDepth)
- minimumSplitDepth = requested < 8 ? 4 * ONE_PLY : 7 * ONE_PLY;
-
while (size() < requested)
push_back(new_thread<Thread>());
}
-// ThreadPool::wait_for_think_finished() waits for main thread to finish the search
-
-void ThreadPool::wait_for_think_finished() {
-
- std::unique_lock<Mutex> lk(main()->mutex);
- sleepCondition.wait(lk, [&]{ return !main()->thinking; });
-}
-
-
// ThreadPool::start_thinking() wakes up the main thread sleeping in
// MainThread::idle_loop() and starts a new search, then returns immediately.
void ThreadPool::start_thinking(const Position& pos, const LimitsType& limits,
StateStackPtr& states) {
- wait_for_think_finished();
-
- SearchTime = now(); // As early as possible
+ main()->join();
Signals.stopOnPonderhit = Signals.firstRootMove = false;
Signals.stop = Signals.failedLowAtRoot = false;
RootMoves.push_back(RootMove(m));
main()->thinking = true;
-
- for (Thread* th : *this)
- th->notify_one();
+ main()->notify_one(); // Wake up main thread: 'thinking' must be already set
}