gpt4 book ai didi

c++ - tbb::concurrent_hash_map - 如果键输入被其他线程阻塞,如何返回

转载 作者:太空宇宙 更新时间:2023-11-04 13:23:22 26 4
gpt4 key购买 nike

我正在编写一个程序,其中有多个线程将条目添加到 (tbb::concurrent_hash_map) HashMap ,同时其他线程遍历该映射并操作 HashMap 上的条目。每次一个线程操作一个条目并使用一个访问器阻塞该条目(这样就不会发生冲突,并且没有其他线程可以访问该条目)。操作数据后,线程插入数据并释放访问器。

我现在的问题是,即使散列映射上的其他条目未被阻塞,一个线程如何访问被阻塞的条目一直在等待,直到该条目的访问者被释放。我想要实现的目标是,线程跳过阻塞的条目并转到下一个非阻塞条目或返回到我的函数。有好的解决办法吗?

以下代码片段作为简短的单线程示例:

...
typdef tbb::concurrent_hash_map<int,unsigned int> typ_hash_map;
typ_hash_map hash_map;
typ_hash_map::accessor acc;
typ_hash_map::accessor acc2;
//hash_map filled with 4 entries...

//block second entry in hash map
typ_hash_map::iterator k = hash_map.begin();
k++;
config.hash_map.insert(acc,k->first);

//travers all entries in hash_map
for(typ_hash_map::iterator j = hash_map.begin();j!=hash_map.end(); j++){
hash_map.find(acc2,j->first); // my problem: return if entry is blocked - at the moment its waiting till acc is released
/*
Do something with acc2->second if entry is not blocked,
else continue;
*/
}
...

最佳答案

你知道遍历tbb::concurrent_hash_map不是线程安全的吗?如果您的代码是串行的,那么就没有什么需要保护的:因此,您不需要持有访问器。

无论如何,长时间锁定元素不是一个好主意,因为它会损害可伸缩性并导致像您这样的死锁,应该在更新完成或读取数据时立即释放。

concurrent_hash_map 的一般规则是:不要在持有第一个访问器时对其他访问器运行任何哈希表操作。

因此,只需在完成访问器 acc 后立即释放它:acc.release()

关于c++ - tbb::concurrent_hash_map - 如果键输入被其他线程阻塞,如何返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com