我正在尝试folly::concurrentHashMap
作为一个非常基本的示例。假设我们有n
个线程,并且每个线程都试图在哈希映射中仅插入一个元素:key = 0
和val=max(map[key], threadId)
。
运行3个线程:线程0,线程1,线程2(它们可以按任何顺序访问地图)
Before running threads: map.find(0) == map.end()
After thread 1 => map[0] will be 1
After thread 0 => map[0] will be 1 (i.e., max(1, 0))
After thread 2 => map[0] will be 2 (i.e., max(1, 2))
folly::ConcurrentHashMap<KeyType, ValType> follyMap;
for (int i = 0; i < numThreads; i++) {
insertionThreads.emplace_back(std::thread([&] {
do {
auto found = follyMap.find(key);
if (found != follyMap.end()) {
ValType oldVal = found->second;
if (oldVal < val) {
std::cout << cnt << std::endl;
auto res = follyMap.assign_if_equal(key, oldVal, val);
cont = !res;
}
break;
} else {
auto res = follyMap.insert(key, val);
cont = !res.second;
}
} while (cont);
}
问题是输出是不确定的且不正确。即,例如,对于前述示例,程序输出0、1或2。然而,正确值仅是2。