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;
}
Boann
  • 48,794
  • 16
  • 117
  • 146
Jack
  • 131
  • 1
  • 8

1 Answers1

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; 
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Is it possible to somehow have one const_accessor and one accessor at the same time? – Jack Jul 24 '17 at 09:21
  • 1
    @Jack - 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). – StoryTeller - Unslander Monica Jul 24 '17 at 09:30