【问题标题】:tbb::concurrent_hash_map - how to return if key-entry is blocked by other threadtbb::concurrent_hash_map - 如果 key-entry 被其他线程阻塞如何返回
【发布时间】:2026-01-20 03:30:01
【问题描述】:

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

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

以下代码 sn-p 作为短单线程示例:

...
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;
            */
          }
...

【问题讨论】:

    标签: c++ multithreading hashmap tbb


    【解决方案1】:

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

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

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

    所以,只要你完成访问器acc 就释放它:acc.release()

    【讨论】:

      最近更新 更多