c++ - tbb并发hashmap实现字典ADT

标签 c++ concurrency hashmap tbb

我正在尝试使用 TBB 的并发 HashMap 实现字典 ADT。我在使用顺序版本时遇到问题。所以我猜我使用 map 函数的方式有问题。 gdb 表示代码在对 erase(key) 的调用中挂起,后者又调用了 lock 例程。闻起来像个僵局。这是更正的代码:

#include<stdio.h>
#include "tbb/concurrent_hash_map.h"
using namespace tbb;
using namespace std;

typedef concurrent_hash_map<unsigned long,bool> tbbMap;
tbbMap map;

int findPercent;
int insertPercent;
int deletePercent;
unsigned long keyRange;
unsigned int lseed;

bool search(unsigned long key)
{
    if(map.count(key))
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool insert(unsigned long key)
{
    if(map.insert(std::make_pair(key,true)))
    {
        return true;
    }
    else
    {
        return(false);
    }
}

bool remove(unsigned long key)
{
    if(map.erase(key))
    {
        return true;
    }
    else
    {
        return(false);
    }
}

void operateOnDictionary()
{
    int chooseOperation;
    unsigned long key;
    int count=0;
    while(count<10)
    {
        chooseOperation = rand_r(&lseed)%100; 
        key = rand_r(&lseed)%keyRange + 1;
        if(chooseOperation < findPercent)
        {
            search(key);
        }
        else if (chooseOperation < insertPercent)
        {
            insert(key);
        }
        else
        {
            remove(key);
        }
        count++;
    }
    printf("done\n");
    return;
}

int main()
{
    findPercent = 10;
    insertPercent= findPercent + 45;
    deletePercent = insertPercent + 45;
    keyRange = 5;
    lseed = 0;
    operateOnDictionary();
}

最佳答案

当然是accessor的错误使用。它应该在范围内,RAII对象,而不是全局对象。

实际发生的是 find()insert() 获取访问器中的锁并且它没有被释放,因为访问器没有被破坏也没有释放锁。然后,erase() 尝试获取相同的锁并挂起,因为它已经被获取了。

顺便说一句,如果您只需要检查 key 是否存在而不需要从中读取任何内容,请考虑使用 count()。如果您不打算在插入后访问元素,也不要使用 insert(with_accessor,key),请使用 insert( std::make_pair(key, value) ) 不使用访问器。

处理访问器意味着一定的运行时开销,因为它本质上是每个元素的锁。例如。比较没有访问器的 concurrent_unordered_map 和有访问器的 concurrent_hash_map 是不公平的。

关于c++ - tbb并发hashmap实现字典ADT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28614297/

相关文章:

java - 等待另一个线程做某事

objective-c - NSURLConnection 与 NSRunLoopCommonModes

java:将 HashMap<String, String> 存储在 ArrayList<Object> 中

c++ mutex cout不打印所有内容

c++ - 使用 ARC 在 C 函数中取消引用 self,引用作为 intptr_t 传递

c++ - C++ 如何获取一段代码的执行时间?

C++ 对非 ASCII 数据文件的支持

c++ - VS2012 中的并发分析 - Reader Writer Locks

Java 对 List<Value> 的 HashMap 值进行排序

java - 我如何处理带计数的 ArrayList,并按函数分组