tbb并发hashmap实现字典ADT

tbb concurrent hashmap to implement dictionary ADT

本文关键字:字典 ADT 实现 hashmap 并发 tbb      更新时间:2023-10-16

我正在尝试使用TBB的并发哈希映射来实现字典ADT。我的顺序版本有问题。所以我想我使用map函数的方式有问题。gdb表示代码挂在对erase(key)的调用中,而CCD_2又调用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("donen");
    return;
}
int main()
{
    findPercent = 10;
    insertPercent= findPercent + 45;
    deletePercent = insertPercent + 45;
    keyRange = 5;
    lseed = 0;
    operateOnDictionary();
}

当然,这是访问器的错误用法。它应该是作用域的RAII对象,而不是全局对象。

实际发生的情况是,find()insert()获取访问器中的锁,但由于访问器未被破坏且未释放锁,因此不会释放该锁。然后,erase()尝试获取相同的锁和hag,因为它已经被获取了。

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

处理访问器意味着一定的运行时开销,因为它本质上是按元素锁定的。例如,比较没有接入者的concurrent_unordered_map和有接入者的CC D_ 11是不公平的。