【问题标题】:tbb concurrent hashmap to implement dictionary ADTtbb并发hashmap实现字典ADT
【发布时间】:2015-02-19 18:37:11
【问题描述】:

我正在尝试使用 TBB 的并发哈希映射来实现字典 ADT。我在使用顺序版本时遇到问题。所以我想我使用地图功能的方式有问题。 gdb 表示代码在调用erase(key) 时挂起,而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();
}

【问题讨论】:

    标签: c++ concurrency hashmap tbb


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 谢谢 :) 我随机搜索、插入或删除字典 ADT 中的键。因此,一个元素有可能被多次访问。为简单起见,我不关心价值。我只关心是否存在密钥search 返回trueinsert 返回false 并删除返回true
    • @arunmoezhi,欢迎,也可以查看count_strings TBB 中的示例
    • 是的,我检查了那个例子。它使用访问器并调用insert()size() 函数。如何在没有访问器的情况下调用find()
    • 您无法在没有访问器的情况下访问数据(在公共接口中:))。但如果不需要,您可以使用count()。不需要写入数据的也请关注const_accessor
    • 哦。我现在不明白。在这种情况下,由于 find 不对数据做任何事情,我应该使用 const_accessor。成功了!!
    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多