【发布时间】: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