Skip to main content

game_tree_search/table/
shared.rs

1//! [`SharedTable`]: one transposition table for several threads (feature `parallel`).
2
3use alloc::vec::Vec;
4use std::sync::{Mutex, MutexGuard, PoisonError};
5
6use super::{Entry, SlotTable, Table, TableKey};
7
8/// A transposition table several threads search with at once: [`SlotTable`] shards, each
9/// behind its own lock.
10///
11/// A key's shard comes from all bits of [`TableKey::slot`], mixed, and its slot within the
12/// shard from the low bits, so threads rarely wait for the same lock. Searchers use it through a
13/// shared reference: `&SharedTable` implements [`Table`], so each thread builds its own
14/// [`Searcher::with_table`](crate::Searcher::with_table)`(&table)`, as
15/// [`deepen_shared`](crate::deepen_shared()) does for Lazy SMP.
16///
17/// Available with the `parallel` feature, which needs `std`.
18#[derive(Debug)]
19pub struct SharedTable<K, M, S> {
20    /// The shards; their number is a power of two.
21    shards: Vec<Mutex<SlotTable<K, M, S>>>,
22}
23
24impl<K: TableKey, M: Clone, S: Clone> SharedTable<K, M, S> {
25    /// A table with about `capacity` slots in `shards` shards, both rounded up to powers of
26    /// two (at least one).
27    ///
28    /// # Panics
29    ///
30    /// Panics if a rounded size does not fit in `usize`.
31    #[must_use]
32    pub fn new(capacity: usize, shards: usize) -> Self {
33        let shards = shards
34            .max(1)
35            .checked_next_power_of_two()
36            .expect("the shard count fits in usize when rounded up");
37        let per_shard = capacity.div_ceil(shards);
38
39        Self {
40            shards: (0..shards)
41                .map(|_| Mutex::new(SlotTable::new(per_shard)))
42                .collect(),
43        }
44    }
45
46    /// The number of slots over all shards.
47    #[must_use]
48    pub fn capacity(&self) -> usize {
49        self.shards.len() * lock(&self.shards[0]).capacity()
50    }
51
52    /// Empties every shard, for example before searching a different game.
53    pub fn clear(&self) {
54        for shard in &self.shards {
55            lock(shard).clear();
56        }
57    }
58
59    /// The shard of `key`: the top bits of its slot bits multiplied by an odd constant
60    /// (Fibonacci hashing), which mixes in every bit, so keys that differ only in their low
61    /// bits, such as small counters, still spread over the shards.
62    fn shard(&self, key: &K) -> MutexGuard<'_, SlotTable<K, M, S>> {
63        lock(&self.shards[self.index(key)])
64    }
65
66    /// The index of `key`'s shard, see [`SharedTable::shard`].
67    fn index(&self, key: &K) -> usize {
68        let bits = self.shards.len().trailing_zeros();
69        let mixed = key.slot().wrapping_mul(0x9e37_79b9_7f4a_7c15);
70        if bits == 0 {
71            return 0;
72        }
73
74        usize::try_from(mixed >> (64 - bits)).expect("a shard index is below the shard count")
75    }
76}
77
78/// Locks `shard`, ignoring a poisoned lock: a thread that panicked mid-store left at worst one
79/// stale slot, which the key check still guards.
80fn lock<T>(shard: &Mutex<T>) -> MutexGuard<'_, T> {
81    shard.lock().unwrap_or_else(PoisonError::into_inner)
82}
83
84impl<K: TableKey, M: Clone, S: Clone> Table<K, M, S> for &SharedTable<K, M, S> {
85    fn probe(&mut self, key: &K) -> Option<Entry<M, S>> {
86        self.shard(key).probe(key)
87    }
88
89    fn store(&mut self, key: K, entry: Entry<M, S>) {
90        self.shard(&key).store(key, entry);
91    }
92}
93
94/// Unit tests for shard selection.
95#[cfg(test)]
96mod tests {
97    use alloc::collections::BTreeSet;
98
99    use super::SharedTable;
100
101    /// Small keys, which differ only in their low bits, still spread over the shards.
102    #[test]
103    fn small_keys_spread_over_the_shards() {
104        let table = SharedTable::<u64, u8, i32>::new(1024, 8);
105        let shards: BTreeSet<usize> = (0..64_u64).map(|key| table.index(&key)).collect();
106        assert!(shards.len() >= 6, "{shards:?}");
107        assert_eq!(SharedTable::<u64, u8, i32>::new(16, 1).index(&5), 0);
108    }
109}