use alloc::vec::Vec;
use core::cell::Cell;
use core::sync::atomic::{AtomicBool, Ordering};
use std::panic;
use std::thread;
use search_core::Budget;
use crate::{Algorithm, Deepening, Hashed, SearchResult, Searcher, Stats, Table, Window};
pub fn deepen_shared<G, B>(
game: &G,
position: &G::Position,
max_depth: u32,
setup: (usize, Algorithm),
table: impl Table<G::Key, G::Move, G::Score> + Copy + Send + Sync,
budget: B,
) -> SearchResult<G::Move, G::Score>
where
G: Hashed + Sync,
G::Position: Sync,
G::Key: Send,
G::Move: Send,
G::Score: Send,
B: Budget<Stats> + Send,
{
let always = |_: &SearchResult<G::Move, G::Score>| true;
deepen_shared_with(game, position, max_depth, setup, table, budget, always)
}
pub fn deepen_shared_with<G, B>(
game: &G,
position: &G::Position,
max_depth: u32,
(threads, algorithm): (usize, Algorithm),
table: impl Table<G::Key, G::Move, G::Score> + Copy + Send + Sync,
budget: B,
deepening: impl Deepening<G::Move, G::Score>,
) -> SearchResult<G::Move, G::Score>
where
G: Hashed + Sync,
G::Position: Sync,
G::Key: Send,
G::Move: Send,
G::Score: Send,
B: Budget<Stats> + Send,
{
let done = &AtomicBool::new(false);
let declined = Cell::new(false);
let searcher = || Searcher::with_table(table).with_algorithm(algorithm);
thread::scope(|scope| {
let stop = Stop(done);
let helpers: Vec<_> = (1..threads.max(1))
.map(|helper| {
let stopped = |_: &Stats| done.load(Ordering::Relaxed);
scope.spawn(move || {
let mut helper_searcher = searcher();
helper_searcher.lead = u32::from(helper % 2 == 1);
helper_searcher.budget_first = true;
helper_searcher.skew = helper;
let result = helper_searcher.deepen(game, position, max_depth, stopped);
let answer = helper_searcher.answered.then_some(result);
if answer
.as_ref()
.is_some_and(|result| finished(result, max_depth))
{
done.store(true, Ordering::Relaxed);
}
answer
})
})
.collect();
let mut budget = budget;
let main_budget = |stats: &Stats| done.load(Ordering::Relaxed) || budget.exhausted(stats);
let watched = Watched {
deepening,
declined: &declined,
};
let main = panic::catch_unwind(panic::AssertUnwindSafe(|| {
searcher().deepen_with(game, position, max_depth, main_budget, watched)
}));
drop(stop);
let main = rethrow(main);
let main_finished = declined.get();
let rank = |result: &SearchResult<G::Move, G::Score>, settled: bool| {
(settled || finished(result, max_depth), result.depth)
};
let mut best_rank = rank(&main, main_finished);
helpers
.into_iter()
.filter_map(|helper| rethrow(helper.join()))
.fold(main, |best, helper| {
let helper_rank = rank(&helper, false);
if helper_rank > best_rank {
best_rank = helper_rank;
helper
} else {
best
}
})
})
}
const fn finished<M, S>(result: &SearchResult<M, S>, max_depth: u32) -> bool {
result.depth == max_depth || result.proven
}
struct Watched<'a, D> {
deepening: D,
declined: &'a Cell<bool>,
}
impl<M, S, D: Deepening<M, S>> Deepening<M, S> for Watched<'_, D> {
fn proceed(&mut self, result: &SearchResult<M, S>) -> bool {
let proceed = self.deepening.proceed(result);
if !proceed {
self.declined.set(true);
}
proceed
}
fn window(&mut self, previous: &SearchResult<M, S>, attempt: u32) -> Window<S> {
self.deepening.window(previous, attempt)
}
}
struct Stop<'a>(&'a AtomicBool);
impl Drop for Stop<'_> {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
pub(crate) fn rethrow<T>(outcome: thread::Result<T>) -> T {
outcome.unwrap_or_else(|panic| panic::resume_unwind(panic))
}