Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I have two accessors for the same element in tbb hash map?

Tags:

c++

tbb

In the below code, if I do not release a1 the code seems to be stuck in an infinite loop inside the map.find function.

What if I need to search for an element in two different parts of the application?

#include <iostream>
#include "tbb/concurrent_hash_map.h"

using namespace std;
using namespace tbb;

void main()
{
    concurrent_hash_map<int, int> map; 

    concurrent_hash_map<int, int>::accessor a1, a2; 

    map.insert(make_pair(1, 111));

    cout << "a1 - " << map.find(a1, 1) << endl; 

    //a1.release();

    cout << "a2 - " << map.find(a2, 1) << endl;
}
like image 776
Jack Avatar asked Jul 24 '17 06:07

Jack


1 Answers

An accessor allows write access. This means a write lock is acquired, and held by no more than a single accessor. You enter a deadlock because the same thread attempts to lock the same element for writing via different accessors.

If all you want is to read the data, then use a const_accessor with find. It will acquire a read lock only. Multiple read locks can be acquired and held without deadlocking.

concurrent_hash_map<int, int>::const_accessor a1, a2; 
like image 163
StoryTeller - Unslander Monica Avatar answered Oct 27 '22 09:10

StoryTeller - Unslander Monica