From 75b6c35cc5189f28e231fd20a36ab810ad2049cd Mon Sep 17 00:00:00 2001 From: Karma Riuk Date: Thu, 6 Feb 2025 23:46:34 +0100 Subject: [PATCH] if the ai found the move before the thinking_time is over, stop the thread to return --- cpp/src/model/ais/ai.cpp | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/cpp/src/model/ais/ai.cpp b/cpp/src/model/ais/ai.cpp index 297368a..31359f0 100644 --- a/cpp/src/model/ais/ai.cpp +++ b/cpp/src/model/ais/ai.cpp @@ -1,17 +1,43 @@ #include "ai.hpp" +#include +#include #include -Move ai::AI::search(const Board& b, bool am_white) { +Move ai::AI::search(const Board& b) { Move result; + std::condition_variable cv; + std::mutex cv_mutex; + double elapsed; + + // Start computation in a separate thread - std::thread computation_thread([&]() { result = _search(b, am_white); }); + std::thread computation_thread([&]() { + auto start = std::chrono::steady_clock::now(); + result = _search(b); + auto end = std::chrono::steady_clock::now(); + elapsed = + std::chrono::duration_cast(end - start) + .count(); + + // Notify the timer thread that computation is done + { + std::lock_guard lock(cv_mutex); + stop_computation = true; + cv.notify_one(); + } + }); // Start a timer thread to stop computation after given time std::thread timer_thread([&]() { - std::this_thread::sleep_for(thinking_time); - stop_computation = true; + std::unique_lock lock(cv_mutex); + if (!cv.wait_for(lock, thinking_time, [&] { + return stop_computation.load(); + })) { + // Timeout reached; set stop flag + stop_computation = true; + } }); // Wait for computation thread to finish @@ -19,5 +45,7 @@ Move ai::AI::search(const Board& b, bool am_white) { // Ensure timer thread is also stopped timer_thread.join(); + + std::cout << "Took " << elapsed << " ms" << std::endl; return result; }