Skip to content

Commit a56c63e

Browse files
committed
Fix race condition caused by init_table failure
1 parent 67d7ae7 commit a56c63e

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/tbprobe.c

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,11 @@ struct PawnEntry {
488488
struct TbHashEntry {
489489
uint64_t key;
490490
struct BaseEntry *ptr;
491+
#ifdef __cplusplus
492+
atomic<bool> error;
493+
#else
494+
atomic_bool error;
495+
#endif
491496
};
492497

493498
static int tbNumPiece, tbNumPawn;
@@ -725,6 +730,7 @@ static void add_to_hash(struct BaseEntry *ptr, uint64_t key)
725730

726731
tbHash[idx].key = key;
727732
tbHash[idx].ptr = ptr;
733+
atomic_init(&tbHash[idx].error, false);
728734
}
729735

730736
#define pchr(i) piece_to_char[QUEEN - (i)]
@@ -1747,7 +1753,7 @@ int probe_table(const Pos *pos, int s, int *success, const int type)
17471753
int hashIdx = key >> (64 - TB_HASHBITS);
17481754
while (tbHash[hashIdx].key && tbHash[hashIdx].key != key)
17491755
hashIdx = (hashIdx + 1) & ((1 << TB_HASHBITS) - 1);
1750-
if (!tbHash[hashIdx].ptr) {
1756+
if (!tbHash[hashIdx].ptr || atomic_load_explicit(&tbHash[hashIdx].error, memory_order_relaxed)) {
17511757
*success = 0;
17521758
return 0;
17531759
}
@@ -1761,11 +1767,16 @@ int probe_table(const Pos *pos, int s, int *success, const int type)
17611767
// Use double-checked locking to reduce locking overhead
17621768
if (!atomic_load_explicit(&be->ready[type], memory_order_acquire)) {
17631769
LOCK(tbMutex);
1770+
if (atomic_load_explicit(&tbHash[hashIdx].error, memory_order_relaxed)) {
1771+
*success = 0;
1772+
UNLOCK(tbMutex);
1773+
return 0;
1774+
}
17641775
if (!atomic_load_explicit(&be->ready[type], memory_order_relaxed)) {
17651776
char str[16];
17661777
prt_str(pos, str, be->key != key);
17671778
if (!init_table(be, str, type)) {
1768-
tbHash[hashIdx].ptr = NULL; // mark as deleted
1779+
atomic_store_explicit(&tbHash[hashIdx].error, true, memory_order_relaxed);
17691780
*success = 0;
17701781
UNLOCK(tbMutex);
17711782
return 0;

0 commit comments

Comments
 (0)