Skip to content

Commit 08d3b46

Browse files
committed
guard against fixed tt insertion race
If insert fails due to the hash already being present, the cached one will be used instead.
1 parent 00ef1d2 commit 08d3b46

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

src/search/dag_classic/search.cc

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2246,13 +2246,18 @@ void SearchWorker::DoBackupUpdateSingleNode(
22462246
#endif
22472247
if (is_tt_miss) {
22482248
#ifdef FIX_TT
2249-
search_->tt_->Insert(node_to_process.hash,
2250-
std::make_unique<std::weak_ptr<LowNode>>(
2251-
node_to_process.tt_low_node));
2249+
// If Insert() fails due to the hash being present, it will return the
2250+
// cached value to be used instead.
2251+
node_to_process.node->SetLowNode(
2252+
search_->tt_
2253+
->Insert(node_to_process.hash,
2254+
std::make_unique<std::weak_ptr<LowNode>>(
2255+
node_to_process.tt_low_node))
2256+
.lock());
22522257
#else
22532258
assert(!tt_iter->second.expired());
2254-
#endif
22552259
node_to_process.node->SetLowNode(node_to_process.tt_low_node);
2260+
#endif
22562261
} else {
22572262
#ifdef FIX_TT
22582263
auto tt_low_node = entry->lock();

src/utils/cache.h

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,9 @@ class HashKeyedCache {
6363

6464
// Inserts the element under key @key with value @val. Unless the key is
6565
// already in the cache.
66-
void Insert(uint64_t key, std::unique_ptr<V> val) {
67-
if (capacity_.load(std::memory_order_relaxed) == 0) return;
66+
// Returns a reference to the inserted element or the one blocking insertion.
67+
const V& Insert(uint64_t key, std::unique_ptr<V> val) {
68+
if (capacity_.load(std::memory_order_relaxed) == 0) return *val;
6869

6970
SpinMutex::Lock lock(mutex_);
7071

@@ -73,7 +74,7 @@ class HashKeyedCache {
7374
if (!hash_[idx].in_use) break;
7475
if (hash_[idx].key == key) {
7576
// Already exists.
76-
return;
77+
return *hash_[idx].value;
7778
}
7879
++idx;
7980
if (idx >= hash_.size()) idx -= hash_.size();
@@ -87,6 +88,7 @@ class HashKeyedCache {
8788
++allocated_;
8889

8990
EvictToCapacity(capacity_);
91+
return *hash_[idx].value;
9092
}
9193

9294
// Checks whether a key exists. Doesn't pin. Of course the next moment the

0 commit comments

Comments
 (0)