6

I am currently using tbb's concurrent hash map to perform concurrent insertions into a hash map. Each key is a string and a value is a vector of integers. I would like to achieve the following: during insertions, if the key does not exist, I insert it and add the value to its vector. If it exists, I simply add the value to its vector.

After inspecting the tbb concurrent hash map API, I noticed that both the find and insert functions return booleans only. So how can I return a pointer to the key if it exists?

Anton
  • 6,349
  • 1
  • 25
  • 53
NewToAndroid
  • 581
  • 7
  • 25

2 Answers2

7

There are methods which require an accessor in theirs arguments. The accessor is basically a pointer coupled with a scoped_lock protecting concurrent access to the element. Without the lock, an element can be modified concurrently resulting in a data-race. So, never use a pointer to element in concurrent_hash_map directly (unless protected by the accessor).

Also, you don't need a find() method for your task since insert() methods create the element if it does not exist.

According to the Reference manual, the hash map has the following methods which will likely satisfy your needs:

bool insert( accessor& result, const Key& key );         // creates new element by default
bool insert( accessor& result, const value_type& value );// creates new element by copying

Here is an example:

{
    hash_map_t::accessor a;
    hash_map.insert( a, key );       // creates by default if not exists, acquires lock
    a->second.my_vector.push_back( value ); // new or old entry, add to vector anyway
} // the accessor's lock is released here
Anton
  • 6,349
  • 1
  • 25
  • 53
  • Is accessor lock a lock on just one record (alike transactional memory) or on whole map (all operations would be locked alike one would do manually with standard std::unordered_map + std::lock)? – DuckQueen Jul 29 '15 at 09:50
  • Just one element is locked by the accessor of course. Please note that it is read-write lock, see const_accessor – Anton Jul 29 '15 at 12:19
0

During insertions, if the key does not exist then key inserted and added the value to its vector. If it exists, return false and I simply add the value to its vector.

{
    hash_map_t::accessor accessor;
   
    bool result = hash_map.insert(accessor, std::make_pair(key, {value})); // creates by default if not exists, acquires lock
    if(result == false)
        accessor->second.push_back(value); // if key exists
} // the accessor's lock is released here
AmirSalar
  • 325
  • 2
  • 14