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; }