TBB task_group使用concurrent_hash_map时挂起

TBB task_group hang when using concurrent_hash_map

本文关键字:map hash 挂起 使用 task group TBB concurrent      更新时间:2023-10-16

我试图在正在运行的任务中使用 tbb::concurrent_hash_map,但我遇到了调用地图的 erase() 会导致任务无限锁定的问题。任何想法下面的代码片段可能有什么问题?

#include <iostream>
#include <boost/date_time.hpp>
#include <tbb/concurrent_hash_map.h>
#include <tbb/task_group.h>
#include <tbb/task_scheduler_init.h>
class BusyTask
{
public:    
    void operator()() {
        typedef tbb::concurrent_hash_map<unsigned int, int> MyMap;
        MyMap m;
        MyMap::accessor a;
        m.insert(a, 1);
        m.erase(1); // The task will lock up at this point
    }
};
int main(int argc, char* argv[])
{
    std::cout << "Started" << std::endl;
    BusyTask busyTask1;
    tbb::task_group taskGroup;
    taskGroup.run(busyTask1);
    taskGroup.wait();
    std::cout << "Finished" << std::endl;
    return 0;
}

我正在使用TBB v4.0.5和GCC 4.7进行测试

正如评论中正确指出的那样,这是锁定范围的问题。 erase(1)需要获取已经通过 insert() 操作获取的相同锁(并且锁不是递归的)。

还请注意哈希映射的 erase(by_accessor) 方法,该方法保证受访问器保护的元素将被擦除,而不是具有相同键的另一个元素。如果并发线程擦除了它(提供相同的密钥)并添加了具有相同密钥的新元素,则可能会发生后者。