O'Reilly logo

Intel Threading Building Blocks by James Reinders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

concurrent_hash_map

A concurrent_hash_map<Key,T,HashCompare> is a hash table that permits concurrent accesses. The table is a map from a key to a type T. The HashCompare traits type defines how to hash a key and how to compare two keys.

Example 5-4 builds a concurrent_hash_map in which the keys are strings and the corresponding data is the number of times each string occurs in the array Data.

Example 5-4. Concurrent hash map

#include "tbb/concurrent_hash_map.h" #include "tbb/blocked_range.h" #include "tbb/parallel_for.h" #include <string> using namespace tbb; using namespace std; // Structure that defines hashing and comparison operations for user's type. struct MyHashCompare { static size_t hash( const string& x ) { size_t h = 0; for( const char* s = x.c_str(); *s; ++s ) h = (h*17)^*s; return h; } //! True if strings are equal static bool equal( const string& x, const string& y ) { return x==y; } }; // A concurrent hash table that maps strings to ints. typedef concurrent_hash_map<string,int,MyHashCompare> StringTable; // Function object for counting occurrences of strings. struct Tally { StringTable& table; Tally( StringTable& table_ ) : table(table_) {} void operator()( const blocked_range<string*> range ) const { for( string* p=range.begin(); p!=range.end(); ++p ) { StringTable::accessor a; table.insert( a, *p ); a->second += 1; } } }; const size_t N = 1000000; string Data[N]; void CountOccurrences() { // Construct empty table. StringTable table; // Put occurrences into the table ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required