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

1

8

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;
}
Straighten answered 24/7, 2017 at 6:34 Comment(0)
C
9

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; 
Cambodia answered 24/7, 2017 at 7:20 Comment(2)
Is it possible to somehow have one const_accessor and one accessor at the same time?Straighten
@Straighten - No. A Write must occur when no-one is reading, so as to avoid corrupting their read data. So no read lock can be acquired while there's a write lock, and vice-versa. In a single thread you'll deadlock again if both those accessors attempt to acquire the data without releasing it. The idea with all accessors is to use them in small blocks, so they don't "cling" to the lock for longer than required. Const ones are just an optimization for the case where synchronization isn't required (everybody just reads, and not writes).Cambodia

© 2022 - 2024 — McMap. All rights reserved.