if the ai found the move before the thinking_time
is over, stop the thread to return
This commit is contained in:
parent
74fa99fe7b
commit
75b6c35cc5
@ -1,17 +1,43 @@
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <ostream>
|
||||
#include <thread>
|
||||
|
||||
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<std::chrono::milliseconds>(end - start)
|
||||
.count();
|
||||
|
||||
// Notify the timer thread that computation is done
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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;
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user