concurrent_hash_map.h 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. /*
  2. Copyright (c) 2005-2020 Intel Corporation
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #ifndef __TBB_concurrent_hash_map_H
  14. #define __TBB_concurrent_hash_map_H
  15. #define __TBB_concurrent_hash_map_H_include_area
  16. #include "internal/_warning_suppress_enable_notice.h"
  17. #include "tbb_stddef.h"
  18. #include <iterator>
  19. #include <utility> // Need std::pair
  20. #include <cstring> // Need std::memset
  21. #include __TBB_STD_SWAP_HEADER
  22. #include "tbb_allocator.h"
  23. #include "spin_rw_mutex.h"
  24. #include "atomic.h"
  25. #include "tbb_exception.h"
  26. #include "tbb_profiling.h"
  27. #include "aligned_space.h"
  28. #include "internal/_tbb_hash_compare_impl.h"
  29. #include "internal/_template_helpers.h"
  30. #include "internal/_allocator_traits.h"
  31. #if __TBB_INITIALIZER_LISTS_PRESENT
  32. #include <initializer_list>
  33. #endif
  34. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  35. #include <typeinfo>
  36. #endif
  37. #if __TBB_STATISTICS
  38. #include <stdio.h>
  39. #endif
  40. #if __TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT && __TBB_CPP11_TUPLE_PRESENT
  41. // Definition of __TBB_CPP11_RVALUE_REF_PRESENT includes __TBB_CPP11_TUPLE_PRESENT
  42. // for most of platforms, tuple present macro was added for logical correctness
  43. #include <tuple>
  44. #endif
  45. namespace tbb {
  46. namespace interface5 {
  47. template<typename Key, typename T, typename HashCompare = tbb_hash_compare<Key>, typename A = tbb_allocator<std::pair<const Key, T> > >
  48. class concurrent_hash_map;
  49. //! @cond INTERNAL
  50. namespace internal {
  51. using namespace tbb::internal;
  52. //! Type of a hash code.
  53. typedef size_t hashcode_t;
  54. //! Node base type
  55. struct hash_map_node_base : tbb::internal::no_copy {
  56. //! Mutex type
  57. typedef spin_rw_mutex mutex_t;
  58. //! Scoped lock type for mutex
  59. typedef mutex_t::scoped_lock scoped_t;
  60. //! Next node in chain
  61. hash_map_node_base *next;
  62. mutex_t mutex;
  63. };
  64. //! Incompleteness flag value
  65. static hash_map_node_base *const rehash_req = reinterpret_cast<hash_map_node_base*>(size_t(3));
  66. //! Rehashed empty bucket flag
  67. static hash_map_node_base *const empty_rehashed = reinterpret_cast<hash_map_node_base*>(size_t(0));
  68. //! base class of concurrent_hash_map
  69. class hash_map_base {
  70. public:
  71. //! Size type
  72. typedef size_t size_type;
  73. //! Type of a hash code.
  74. typedef size_t hashcode_t;
  75. //! Segment index type
  76. typedef size_t segment_index_t;
  77. //! Node base type
  78. typedef hash_map_node_base node_base;
  79. //! Bucket type
  80. struct bucket : tbb::internal::no_copy {
  81. //! Mutex type for buckets
  82. typedef spin_rw_mutex mutex_t;
  83. //! Scoped lock type for mutex
  84. typedef mutex_t::scoped_lock scoped_t;
  85. mutex_t mutex;
  86. node_base *node_list;
  87. };
  88. //! Count of segments in the first block
  89. static size_type const embedded_block = 1;
  90. //! Count of segments in the first block
  91. static size_type const embedded_buckets = 1<<embedded_block;
  92. //! Count of segments in the first block
  93. static size_type const first_block = 8; //including embedded_block. perfect with bucket size 16, so the allocations are power of 4096
  94. //! Size of a pointer / table size
  95. static size_type const pointers_per_table = sizeof(segment_index_t) * 8; // one segment per bit
  96. //! Segment pointer
  97. typedef bucket *segment_ptr_t;
  98. //! Segment pointers table type
  99. typedef segment_ptr_t segments_table_t[pointers_per_table];
  100. //! Hash mask = sum of allocated segment sizes - 1
  101. atomic<hashcode_t> my_mask;
  102. //! Segment pointers table. Also prevents false sharing between my_mask and my_size
  103. segments_table_t my_table;
  104. //! Size of container in stored items
  105. atomic<size_type> my_size; // It must be in separate cache line from my_mask due to performance effects
  106. //! Zero segment
  107. bucket my_embedded_segment[embedded_buckets];
  108. #if __TBB_STATISTICS
  109. atomic<unsigned> my_info_resizes; // concurrent ones
  110. mutable atomic<unsigned> my_info_restarts; // race collisions
  111. atomic<unsigned> my_info_rehashes; // invocations of rehash_bucket
  112. #endif
  113. //! Constructor
  114. hash_map_base() {
  115. std::memset(my_table, 0, sizeof(my_table));
  116. my_mask = 0;
  117. my_size = 0;
  118. std::memset(my_embedded_segment, 0, sizeof(my_embedded_segment));
  119. for( size_type i = 0; i < embedded_block; i++ ) // fill the table
  120. my_table[i] = my_embedded_segment + segment_base(i);
  121. my_mask = embedded_buckets - 1;
  122. __TBB_ASSERT( embedded_block <= first_block, "The first block number must include embedded blocks");
  123. #if __TBB_STATISTICS
  124. my_info_resizes = 0; // concurrent ones
  125. my_info_restarts = 0; // race collisions
  126. my_info_rehashes = 0; // invocations of rehash_bucket
  127. #endif
  128. }
  129. //! @return segment index of given index in the array
  130. static segment_index_t segment_index_of( size_type index ) {
  131. return segment_index_t( __TBB_Log2( index|1 ) );
  132. }
  133. //! @return the first array index of given segment
  134. static segment_index_t segment_base( segment_index_t k ) {
  135. return (segment_index_t(1)<<k & ~segment_index_t(1));
  136. }
  137. //! @return segment size except for @arg k == 0
  138. static size_type segment_size( segment_index_t k ) {
  139. return size_type(1)<<k; // fake value for k==0
  140. }
  141. //! @return true if @arg ptr is valid pointer
  142. static bool is_valid( void *ptr ) {
  143. return reinterpret_cast<uintptr_t>(ptr) > uintptr_t(63);
  144. }
  145. //! Initialize buckets
  146. static void init_buckets( segment_ptr_t ptr, size_type sz, bool is_initial ) {
  147. if( is_initial ) std::memset( static_cast<void*>(ptr), 0, sz*sizeof(bucket) );
  148. else for(size_type i = 0; i < sz; i++, ptr++) {
  149. *reinterpret_cast<intptr_t*>(&ptr->mutex) = 0;
  150. ptr->node_list = rehash_req;
  151. }
  152. }
  153. //! Add node @arg n to bucket @arg b
  154. static void add_to_bucket( bucket *b, node_base *n ) {
  155. __TBB_ASSERT(b->node_list != rehash_req, NULL);
  156. n->next = b->node_list;
  157. b->node_list = n; // its under lock and flag is set
  158. }
  159. //! Exception safety helper
  160. struct enable_segment_failsafe : tbb::internal::no_copy {
  161. segment_ptr_t *my_segment_ptr;
  162. enable_segment_failsafe(segments_table_t &table, segment_index_t k) : my_segment_ptr(&table[k]) {}
  163. ~enable_segment_failsafe() {
  164. if( my_segment_ptr ) *my_segment_ptr = 0; // indicate no allocation in progress
  165. }
  166. };
  167. //! Enable segment
  168. template<typename Allocator>
  169. void enable_segment( segment_index_t k, const Allocator& allocator, bool is_initial = false ) {
  170. typedef typename tbb::internal::allocator_rebind<Allocator, bucket>::type bucket_allocator_type;
  171. typedef tbb::internal::allocator_traits<bucket_allocator_type> bucket_allocator_traits;
  172. bucket_allocator_type bucket_allocator(allocator);
  173. __TBB_ASSERT( k, "Zero segment must be embedded" );
  174. enable_segment_failsafe watchdog( my_table, k );
  175. size_type sz;
  176. __TBB_ASSERT( !is_valid(my_table[k]), "Wrong concurrent assignment");
  177. if( k >= first_block ) {
  178. sz = segment_size( k );
  179. segment_ptr_t ptr = bucket_allocator_traits::allocate(bucket_allocator, sz);
  180. init_buckets( ptr, sz, is_initial );
  181. itt_hide_store_word( my_table[k], ptr );
  182. sz <<= 1;// double it to get entire capacity of the container
  183. } else { // the first block
  184. __TBB_ASSERT( k == embedded_block, "Wrong segment index" );
  185. sz = segment_size( first_block );
  186. segment_ptr_t ptr = bucket_allocator_traits::allocate(bucket_allocator, sz - embedded_buckets);
  187. init_buckets( ptr, sz - embedded_buckets, is_initial );
  188. ptr -= segment_base(embedded_block);
  189. for(segment_index_t i = embedded_block; i < first_block; i++) // calc the offsets
  190. itt_hide_store_word( my_table[i], ptr + segment_base(i) );
  191. }
  192. itt_store_word_with_release( my_mask, sz-1 );
  193. watchdog.my_segment_ptr = 0;
  194. }
  195. template<typename Allocator>
  196. void delete_segment(segment_index_t s, const Allocator& allocator) {
  197. typedef typename tbb::internal::allocator_rebind<Allocator, bucket>::type bucket_allocator_type;
  198. typedef tbb::internal::allocator_traits<bucket_allocator_type> bucket_allocator_traits;
  199. bucket_allocator_type bucket_allocator(allocator);
  200. segment_ptr_t buckets_ptr = my_table[s];
  201. size_type sz = segment_size( s ? s : 1 );
  202. if( s >= first_block) // the first segment or the next
  203. bucket_allocator_traits::deallocate(bucket_allocator, buckets_ptr, sz);
  204. else if( s == embedded_block && embedded_block != first_block )
  205. bucket_allocator_traits::deallocate(bucket_allocator, buckets_ptr,
  206. segment_size(first_block) - embedded_buckets);
  207. if( s >= embedded_block ) my_table[s] = 0;
  208. }
  209. //! Get bucket by (masked) hashcode
  210. bucket *get_bucket( hashcode_t h ) const throw() { // TODO: add throw() everywhere?
  211. segment_index_t s = segment_index_of( h );
  212. h -= segment_base(s);
  213. segment_ptr_t seg = my_table[s];
  214. __TBB_ASSERT( is_valid(seg), "hashcode must be cut by valid mask for allocated segments" );
  215. return &seg[h];
  216. }
  217. // internal serial rehashing helper
  218. void mark_rehashed_levels( hashcode_t h ) throw () {
  219. segment_index_t s = segment_index_of( h );
  220. while( segment_ptr_t seg = my_table[++s] )
  221. if( seg[h].node_list == rehash_req ) {
  222. seg[h].node_list = empty_rehashed;
  223. mark_rehashed_levels( h + ((hashcode_t)1<<s) ); // optimized segment_base(s)
  224. }
  225. }
  226. //! Check for mask race
  227. // Splitting into two functions should help inlining
  228. inline bool check_mask_race( const hashcode_t h, hashcode_t &m ) const {
  229. hashcode_t m_now, m_old = m;
  230. m_now = (hashcode_t) itt_load_word_with_acquire( my_mask );
  231. if( m_old != m_now )
  232. return check_rehashing_collision( h, m_old, m = m_now );
  233. return false;
  234. }
  235. //! Process mask race, check for rehashing collision
  236. bool check_rehashing_collision( const hashcode_t h, hashcode_t m_old, hashcode_t m ) const {
  237. __TBB_ASSERT(m_old != m, NULL); // TODO?: m arg could be optimized out by passing h = h&m
  238. if( (h & m_old) != (h & m) ) { // mask changed for this hashcode, rare event
  239. // condition above proves that 'h' has some other bits set beside 'm_old'
  240. // find next applicable mask after m_old //TODO: look at bsl instruction
  241. for( ++m_old; !(h & m_old); m_old <<= 1 ) // at maximum few rounds depending on the first block size
  242. ;
  243. m_old = (m_old<<1) - 1; // get full mask from a bit
  244. __TBB_ASSERT((m_old&(m_old+1))==0 && m_old <= m, NULL);
  245. // check whether it is rehashing/ed
  246. if( itt_load_word_with_acquire(get_bucket(h & m_old)->node_list) != rehash_req )
  247. {
  248. #if __TBB_STATISTICS
  249. my_info_restarts++; // race collisions
  250. #endif
  251. return true;
  252. }
  253. }
  254. return false;
  255. }
  256. //! Insert a node and check for load factor. @return segment index to enable.
  257. segment_index_t insert_new_node( bucket *b, node_base *n, hashcode_t mask ) {
  258. size_type sz = ++my_size; // prefix form is to enforce allocation after the first item inserted
  259. add_to_bucket( b, n );
  260. // check load factor
  261. if( sz >= mask ) { // TODO: add custom load_factor
  262. segment_index_t new_seg = __TBB_Log2( mask+1 ); //optimized segment_index_of
  263. __TBB_ASSERT( is_valid(my_table[new_seg-1]), "new allocations must not publish new mask until segment has allocated");
  264. static const segment_ptr_t is_allocating = (segment_ptr_t)2;
  265. if( !itt_hide_load_word(my_table[new_seg])
  266. && as_atomic(my_table[new_seg]).compare_and_swap(is_allocating, NULL) == NULL )
  267. return new_seg; // The value must be processed
  268. }
  269. return 0;
  270. }
  271. //! Prepare enough segments for number of buckets
  272. template<typename Allocator>
  273. void reserve(size_type buckets, const Allocator& allocator) {
  274. if( !buckets-- ) return;
  275. bool is_initial = !my_size;
  276. for( size_type m = my_mask; buckets > m; m = my_mask )
  277. enable_segment( segment_index_of( m+1 ), allocator, is_initial );
  278. }
  279. //! Swap hash_map_bases
  280. void internal_swap(hash_map_base &table) {
  281. using std::swap;
  282. swap(this->my_mask, table.my_mask);
  283. swap(this->my_size, table.my_size);
  284. for(size_type i = 0; i < embedded_buckets; i++)
  285. swap(this->my_embedded_segment[i].node_list, table.my_embedded_segment[i].node_list);
  286. for(size_type i = embedded_block; i < pointers_per_table; i++)
  287. swap(this->my_table[i], table.my_table[i]);
  288. }
  289. #if __TBB_CPP11_RVALUE_REF_PRESENT
  290. void internal_move(hash_map_base&& other) {
  291. my_mask = other.my_mask;
  292. other.my_mask = embedded_buckets - 1;
  293. my_size = other.my_size;
  294. other.my_size = 0;
  295. for(size_type i = 0; i < embedded_buckets; ++i) {
  296. my_embedded_segment[i].node_list = other.my_embedded_segment[i].node_list;
  297. other.my_embedded_segment[i].node_list = NULL;
  298. }
  299. for(size_type i = embedded_block; i < pointers_per_table; ++i) {
  300. my_table[i] = other.my_table[i];
  301. other.my_table[i] = NULL;
  302. }
  303. }
  304. #endif // __TBB_CPP11_RVALUE_REF_PRESENT
  305. };
  306. template<typename Iterator>
  307. class hash_map_range;
  308. //! Meets requirements of a forward iterator for STL */
  309. /** Value is either the T or const T type of the container.
  310. @ingroup containers */
  311. template<typename Container, typename Value>
  312. class hash_map_iterator
  313. : public std::iterator<std::forward_iterator_tag,Value>
  314. {
  315. typedef Container map_type;
  316. typedef typename Container::node node;
  317. typedef hash_map_base::node_base node_base;
  318. typedef hash_map_base::bucket bucket;
  319. template<typename C, typename T, typename U>
  320. friend bool operator==( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
  321. template<typename C, typename T, typename U>
  322. friend bool operator!=( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
  323. template<typename C, typename T, typename U>
  324. friend ptrdiff_t operator-( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
  325. template<typename C, typename U>
  326. friend class hash_map_iterator;
  327. template<typename I>
  328. friend class hash_map_range;
  329. void advance_to_next_bucket() { // TODO?: refactor to iterator_base class
  330. size_t k = my_index+1;
  331. __TBB_ASSERT( my_bucket, "advancing an invalid iterator?");
  332. while( k <= my_map->my_mask ) {
  333. // Following test uses 2's-complement wizardry
  334. if( k&(k-2) ) // not the beginning of a segment
  335. ++my_bucket;
  336. else my_bucket = my_map->get_bucket( k );
  337. my_node = static_cast<node*>( my_bucket->node_list );
  338. if( hash_map_base::is_valid(my_node) ) {
  339. my_index = k; return;
  340. }
  341. ++k;
  342. }
  343. my_bucket = 0; my_node = 0; my_index = k; // the end
  344. }
  345. #if !defined(_MSC_VER) || defined(__INTEL_COMPILER)
  346. template<typename Key, typename T, typename HashCompare, typename A>
  347. friend class interface5::concurrent_hash_map;
  348. #else
  349. public: // workaround
  350. #endif
  351. //! concurrent_hash_map over which we are iterating.
  352. const Container *my_map;
  353. //! Index in hash table for current item
  354. size_t my_index;
  355. //! Pointer to bucket
  356. const bucket *my_bucket;
  357. //! Pointer to node that has current item
  358. node *my_node;
  359. hash_map_iterator( const Container &map, size_t index, const bucket *b, node_base *n );
  360. public:
  361. //! Construct undefined iterator
  362. hash_map_iterator(): my_map(), my_index(), my_bucket(), my_node() {}
  363. hash_map_iterator( const hash_map_iterator<Container,typename Container::value_type> &other ) :
  364. my_map(other.my_map),
  365. my_index(other.my_index),
  366. my_bucket(other.my_bucket),
  367. my_node(other.my_node)
  368. {}
  369. hash_map_iterator& operator=( const hash_map_iterator<Container,typename Container::value_type> &other ) {
  370. my_map = other.my_map;
  371. my_index = other.my_index;
  372. my_bucket = other.my_bucket;
  373. my_node = other.my_node;
  374. return *this;
  375. }
  376. Value& operator*() const {
  377. __TBB_ASSERT( hash_map_base::is_valid(my_node), "iterator uninitialized or at end of container?" );
  378. return my_node->value();
  379. }
  380. Value* operator->() const {return &operator*();}
  381. hash_map_iterator& operator++();
  382. //! Post increment
  383. hash_map_iterator operator++(int) {
  384. hash_map_iterator old(*this);
  385. operator++();
  386. return old;
  387. }
  388. };
  389. template<typename Container, typename Value>
  390. hash_map_iterator<Container,Value>::hash_map_iterator( const Container &map, size_t index, const bucket *b, node_base *n ) :
  391. my_map(&map),
  392. my_index(index),
  393. my_bucket(b),
  394. my_node( static_cast<node*>(n) )
  395. {
  396. if( b && !hash_map_base::is_valid(n) )
  397. advance_to_next_bucket();
  398. }
  399. template<typename Container, typename Value>
  400. hash_map_iterator<Container,Value>& hash_map_iterator<Container,Value>::operator++() {
  401. my_node = static_cast<node*>( my_node->next );
  402. if( !my_node ) advance_to_next_bucket();
  403. return *this;
  404. }
  405. template<typename Container, typename T, typename U>
  406. bool operator==( const hash_map_iterator<Container,T>& i, const hash_map_iterator<Container,U>& j ) {
  407. return i.my_node == j.my_node && i.my_map == j.my_map;
  408. }
  409. template<typename Container, typename T, typename U>
  410. bool operator!=( const hash_map_iterator<Container,T>& i, const hash_map_iterator<Container,U>& j ) {
  411. return i.my_node != j.my_node || i.my_map != j.my_map;
  412. }
  413. //! Range class used with concurrent_hash_map
  414. /** @ingroup containers */
  415. template<typename Iterator>
  416. class hash_map_range {
  417. typedef typename Iterator::map_type map_type;
  418. Iterator my_begin;
  419. Iterator my_end;
  420. mutable Iterator my_midpoint;
  421. size_t my_grainsize;
  422. //! Set my_midpoint to point approximately half way between my_begin and my_end.
  423. void set_midpoint() const;
  424. template<typename U> friend class hash_map_range;
  425. public:
  426. //! Type for size of a range
  427. typedef std::size_t size_type;
  428. typedef typename Iterator::value_type value_type;
  429. typedef typename Iterator::reference reference;
  430. typedef typename Iterator::difference_type difference_type;
  431. typedef Iterator iterator;
  432. //! True if range is empty.
  433. bool empty() const {return my_begin==my_end;}
  434. //! True if range can be partitioned into two subranges.
  435. bool is_divisible() const {
  436. return my_midpoint!=my_end;
  437. }
  438. //! Split range.
  439. hash_map_range( hash_map_range& r, split ) :
  440. my_end(r.my_end),
  441. my_grainsize(r.my_grainsize)
  442. {
  443. r.my_end = my_begin = r.my_midpoint;
  444. __TBB_ASSERT( !empty(), "Splitting despite the range is not divisible" );
  445. __TBB_ASSERT( !r.empty(), "Splitting despite the range is not divisible" );
  446. set_midpoint();
  447. r.set_midpoint();
  448. }
  449. //! type conversion
  450. template<typename U>
  451. hash_map_range( hash_map_range<U>& r) :
  452. my_begin(r.my_begin),
  453. my_end(r.my_end),
  454. my_midpoint(r.my_midpoint),
  455. my_grainsize(r.my_grainsize)
  456. {}
  457. //! Init range with container and grainsize specified
  458. hash_map_range( const map_type &map, size_type grainsize_ = 1 ) :
  459. my_begin( Iterator( map, 0, map.my_embedded_segment, map.my_embedded_segment->node_list ) ),
  460. my_end( Iterator( map, map.my_mask + 1, 0, 0 ) ),
  461. my_grainsize( grainsize_ )
  462. {
  463. __TBB_ASSERT( grainsize_>0, "grainsize must be positive" );
  464. set_midpoint();
  465. }
  466. const Iterator& begin() const {return my_begin;}
  467. const Iterator& end() const {return my_end;}
  468. //! The grain size for this range.
  469. size_type grainsize() const {return my_grainsize;}
  470. };
  471. template<typename Iterator>
  472. void hash_map_range<Iterator>::set_midpoint() const {
  473. // Split by groups of nodes
  474. size_t m = my_end.my_index-my_begin.my_index;
  475. if( m > my_grainsize ) {
  476. m = my_begin.my_index + m/2u;
  477. hash_map_base::bucket *b = my_begin.my_map->get_bucket(m);
  478. my_midpoint = Iterator(*my_begin.my_map,m,b,b->node_list);
  479. } else {
  480. my_midpoint = my_end;
  481. }
  482. __TBB_ASSERT( my_begin.my_index <= my_midpoint.my_index,
  483. "my_begin is after my_midpoint" );
  484. __TBB_ASSERT( my_midpoint.my_index <= my_end.my_index,
  485. "my_midpoint is after my_end" );
  486. __TBB_ASSERT( my_begin != my_midpoint || my_begin == my_end,
  487. "[my_begin, my_midpoint) range should not be empty" );
  488. }
  489. } // internal
  490. //! @endcond
  491. #if _MSC_VER && !defined(__INTEL_COMPILER)
  492. // Suppress "conditional expression is constant" warning.
  493. #pragma warning( push )
  494. #pragma warning( disable: 4127 )
  495. #endif
  496. //! Unordered map from Key to T.
  497. /** concurrent_hash_map is associative container with concurrent access.
  498. @par Compatibility
  499. The class meets all Container Requirements from C++ Standard (See ISO/IEC 14882:2003(E), clause 23.1).
  500. @par Exception Safety
  501. - Hash function is not permitted to throw an exception. User-defined types Key and T are forbidden from throwing an exception in destructors.
  502. - If exception happens during insert() operations, it has no effect (unless exception raised by HashCompare::hash() function during grow_segment).
  503. - If exception happens during operator=() operation, the container can have a part of source items, and methods size() and empty() can return wrong results.
  504. @par Changes since TBB 2.1
  505. - Replaced internal algorithm and data structure. Patent is pending.
  506. - Added buckets number argument for constructor
  507. @par Changes since TBB 2.0
  508. - Fixed exception-safety
  509. - Added template argument for allocator
  510. - Added allocator argument in constructors
  511. - Added constructor from a range of iterators
  512. - Added several new overloaded insert() methods
  513. - Added get_allocator()
  514. - Added swap()
  515. - Added count()
  516. - Added overloaded erase(accessor &) and erase(const_accessor&)
  517. - Added equal_range() [const]
  518. - Added [const_]pointer, [const_]reference, and allocator_type types
  519. - Added global functions: operator==(), operator!=(), and swap()
  520. @ingroup containers */
  521. template<typename Key, typename T, typename HashCompare, typename Allocator>
  522. class concurrent_hash_map : protected internal::hash_map_base {
  523. template<typename Container, typename Value>
  524. friend class internal::hash_map_iterator;
  525. template<typename I>
  526. friend class internal::hash_map_range;
  527. public:
  528. typedef Key key_type;
  529. typedef T mapped_type;
  530. typedef std::pair<const Key,T> value_type;
  531. typedef hash_map_base::size_type size_type;
  532. typedef ptrdiff_t difference_type;
  533. typedef value_type *pointer;
  534. typedef const value_type *const_pointer;
  535. typedef value_type &reference;
  536. typedef const value_type &const_reference;
  537. typedef internal::hash_map_iterator<concurrent_hash_map,value_type> iterator;
  538. typedef internal::hash_map_iterator<concurrent_hash_map,const value_type> const_iterator;
  539. typedef internal::hash_map_range<iterator> range_type;
  540. typedef internal::hash_map_range<const_iterator> const_range_type;
  541. typedef Allocator allocator_type;
  542. protected:
  543. friend class const_accessor;
  544. class node;
  545. typedef typename tbb::internal::allocator_rebind<Allocator, node>::type node_allocator_type;
  546. typedef tbb::internal::allocator_traits<node_allocator_type> node_allocator_traits;
  547. node_allocator_type my_allocator;
  548. HashCompare my_hash_compare;
  549. class node : public node_base {
  550. tbb::aligned_space<value_type> my_value;
  551. public:
  552. value_type* storage() { return my_value.begin(); }
  553. value_type& value() { return *storage(); }
  554. };
  555. void delete_node( node_base *n ) {
  556. node_allocator_traits::destroy(my_allocator, static_cast<node*>(n)->storage());
  557. node_allocator_traits::destroy(my_allocator, static_cast<node*>(n));
  558. node_allocator_traits::deallocate(my_allocator, static_cast<node*>(n), 1);
  559. }
  560. struct node_scoped_guard : tbb::internal::no_copy {
  561. node* my_node;
  562. node_allocator_type& my_alloc;
  563. node_scoped_guard(node* n, node_allocator_type& alloc) : my_node(n), my_alloc(alloc) {}
  564. ~node_scoped_guard() {
  565. if(my_node) {
  566. node_allocator_traits::destroy(my_alloc, my_node);
  567. node_allocator_traits::deallocate(my_alloc, my_node, 1);
  568. }
  569. }
  570. void dismiss() { my_node = NULL; }
  571. };
  572. #if __TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  573. template<typename... Args>
  574. static node* create_node(node_allocator_type& allocator, Args&&... args)
  575. #else
  576. template<typename Arg1, typename Arg2>
  577. static node* create_node(node_allocator_type& allocator, __TBB_FORWARDING_REF(Arg1) arg1, __TBB_FORWARDING_REF(Arg2) arg2)
  578. #endif
  579. {
  580. node* node_ptr = node_allocator_traits::allocate(allocator, 1);
  581. node_scoped_guard guard(node_ptr, allocator);
  582. node_allocator_traits::construct(allocator, node_ptr);
  583. #if __TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  584. node_allocator_traits::construct(allocator, node_ptr->storage(), std::forward<Args>(args)...);
  585. #else
  586. node_allocator_traits::construct(allocator, node_ptr->storage(), tbb::internal::forward<Arg1>(arg1), tbb::internal::forward<Arg2>(arg2));
  587. #endif
  588. guard.dismiss();
  589. return node_ptr;
  590. }
  591. static node* allocate_node_copy_construct(node_allocator_type& allocator, const Key &key, const T * t){
  592. return create_node(allocator, key, *t);
  593. }
  594. #if __TBB_CPP11_RVALUE_REF_PRESENT
  595. static node* allocate_node_move_construct(node_allocator_type& allocator, const Key &key, const T * t){
  596. return create_node(allocator, key, std::move(*const_cast<T*>(t)));
  597. }
  598. #endif
  599. static node* allocate_node_default_construct(node_allocator_type& allocator, const Key &key, const T * ){
  600. #if __TBB_CPP11_RVALUE_REF_PRESENT && __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT && __TBB_CPP11_TUPLE_PRESENT
  601. // Emplace construct an empty T object inside the pair
  602. return create_node(allocator, std::piecewise_construct,
  603. std::forward_as_tuple(key), std::forward_as_tuple());
  604. #else
  605. // Use of a temporary object is impossible, because create_node takes a non-const reference.
  606. // copy-initialization is possible because T is already required to be CopyConstructible.
  607. T obj = T();
  608. return create_node(allocator, key, tbb::internal::move(obj));
  609. #endif
  610. }
  611. static node* do_not_allocate_node(node_allocator_type& , const Key &, const T * ){
  612. __TBB_ASSERT(false,"this dummy function should not be called");
  613. return NULL;
  614. }
  615. node *search_bucket( const key_type &key, bucket *b ) const {
  616. node *n = static_cast<node*>( b->node_list );
  617. while( is_valid(n) && !my_hash_compare.equal(key, n->value().first) )
  618. n = static_cast<node*>( n->next );
  619. __TBB_ASSERT(n != internal::rehash_req, "Search can be executed only for rehashed bucket");
  620. return n;
  621. }
  622. //! bucket accessor is to find, rehash, acquire a lock, and access a bucket
  623. class bucket_accessor : public bucket::scoped_t {
  624. bucket *my_b;
  625. public:
  626. bucket_accessor( concurrent_hash_map *base, const hashcode_t h, bool writer = false ) { acquire( base, h, writer ); }
  627. //! find a bucket by masked hashcode, optionally rehash, and acquire the lock
  628. inline void acquire( concurrent_hash_map *base, const hashcode_t h, bool writer = false ) {
  629. my_b = base->get_bucket( h );
  630. // TODO: actually, notification is unnecessary here, just hiding double-check
  631. if( itt_load_word_with_acquire(my_b->node_list) == internal::rehash_req
  632. && try_acquire( my_b->mutex, /*write=*/true ) )
  633. {
  634. if( my_b->node_list == internal::rehash_req ) base->rehash_bucket( my_b, h ); //recursive rehashing
  635. }
  636. else bucket::scoped_t::acquire( my_b->mutex, writer );
  637. __TBB_ASSERT( my_b->node_list != internal::rehash_req, NULL);
  638. }
  639. //! check whether bucket is locked for write
  640. bool is_writer() { return bucket::scoped_t::is_writer; }
  641. //! get bucket pointer
  642. bucket *operator() () { return my_b; }
  643. };
  644. // TODO refactor to hash_base
  645. void rehash_bucket( bucket *b_new, const hashcode_t h ) {
  646. __TBB_ASSERT( *(intptr_t*)(&b_new->mutex), "b_new must be locked (for write)");
  647. __TBB_ASSERT( h > 1, "The lowermost buckets can't be rehashed" );
  648. __TBB_store_with_release(b_new->node_list, internal::empty_rehashed); // mark rehashed
  649. hashcode_t mask = ( 1u<<__TBB_Log2( h ) ) - 1; // get parent mask from the topmost bit
  650. #if __TBB_STATISTICS
  651. my_info_rehashes++; // invocations of rehash_bucket
  652. #endif
  653. bucket_accessor b_old( this, h & mask );
  654. mask = (mask<<1) | 1; // get full mask for new bucket
  655. __TBB_ASSERT( (mask&(mask+1))==0 && (h & mask) == h, NULL );
  656. restart:
  657. for( node_base **p = &b_old()->node_list, *n = __TBB_load_with_acquire(*p); is_valid(n); n = *p ) {
  658. hashcode_t c = my_hash_compare.hash( static_cast<node*>(n)->value().first );
  659. #if TBB_USE_ASSERT
  660. hashcode_t bmask = h & (mask>>1);
  661. bmask = bmask==0? 1 : ( 1u<<(__TBB_Log2( bmask )+1 ) ) - 1; // minimal mask of parent bucket
  662. __TBB_ASSERT( (c & bmask) == (h & bmask), "hash() function changed for key in table" );
  663. #endif
  664. if( (c & mask) == h ) {
  665. if( !b_old.is_writer() )
  666. if( !b_old.upgrade_to_writer() ) {
  667. goto restart; // node ptr can be invalid due to concurrent erase
  668. }
  669. *p = n->next; // exclude from b_old
  670. add_to_bucket( b_new, n );
  671. } else p = &n->next; // iterate to next item
  672. }
  673. }
  674. struct call_clear_on_leave {
  675. concurrent_hash_map* my_ch_map;
  676. call_clear_on_leave( concurrent_hash_map* a_ch_map ) : my_ch_map(a_ch_map) {}
  677. void dismiss() {my_ch_map = 0;}
  678. ~call_clear_on_leave(){
  679. if (my_ch_map){
  680. my_ch_map->clear();
  681. }
  682. }
  683. };
  684. public:
  685. class accessor;
  686. //! Combines data access, locking, and garbage collection.
  687. class const_accessor : private node::scoped_t /*which derived from no_copy*/ {
  688. friend class concurrent_hash_map<Key,T,HashCompare,Allocator>;
  689. friend class accessor;
  690. public:
  691. //! Type of value
  692. typedef const typename concurrent_hash_map::value_type value_type;
  693. //! True if result is empty.
  694. bool empty() const { return !my_node; }
  695. //! Set to null
  696. void release() {
  697. if( my_node ) {
  698. node::scoped_t::release();
  699. my_node = 0;
  700. }
  701. }
  702. //! Return reference to associated value in hash table.
  703. const_reference operator*() const {
  704. __TBB_ASSERT( my_node, "attempt to dereference empty accessor" );
  705. return my_node->value();
  706. }
  707. //! Return pointer to associated value in hash table.
  708. const_pointer operator->() const {
  709. return &operator*();
  710. }
  711. //! Create empty result
  712. const_accessor() : my_node(NULL) {}
  713. //! Destroy result after releasing the underlying reference.
  714. ~const_accessor() {
  715. my_node = NULL; // scoped lock's release() is called in its destructor
  716. }
  717. protected:
  718. bool is_writer() { return node::scoped_t::is_writer; }
  719. node *my_node;
  720. hashcode_t my_hash;
  721. };
  722. //! Allows write access to elements and combines data access, locking, and garbage collection.
  723. class accessor: public const_accessor {
  724. public:
  725. //! Type of value
  726. typedef typename concurrent_hash_map::value_type value_type;
  727. //! Return reference to associated value in hash table.
  728. reference operator*() const {
  729. __TBB_ASSERT( this->my_node, "attempt to dereference empty accessor" );
  730. return this->my_node->value();
  731. }
  732. //! Return pointer to associated value in hash table.
  733. pointer operator->() const {
  734. return &operator*();
  735. }
  736. };
  737. //! Construct empty table.
  738. explicit concurrent_hash_map( const allocator_type &a = allocator_type() )
  739. : internal::hash_map_base(), my_allocator(a)
  740. {}
  741. explicit concurrent_hash_map( const HashCompare& compare, const allocator_type& a = allocator_type() )
  742. : internal::hash_map_base(), my_allocator(a), my_hash_compare(compare)
  743. {}
  744. //! Construct empty table with n preallocated buckets. This number serves also as initial concurrency level.
  745. concurrent_hash_map( size_type n, const allocator_type &a = allocator_type() )
  746. : internal::hash_map_base(), my_allocator(a)
  747. {
  748. reserve( n, my_allocator );
  749. }
  750. concurrent_hash_map( size_type n, const HashCompare& compare, const allocator_type& a = allocator_type() )
  751. : internal::hash_map_base(), my_allocator(a), my_hash_compare(compare)
  752. {
  753. reserve( n, my_allocator );
  754. }
  755. //! Copy constructor
  756. concurrent_hash_map( const concurrent_hash_map &table )
  757. : internal::hash_map_base(),
  758. my_allocator(node_allocator_traits::select_on_container_copy_construction(table.get_allocator()))
  759. {
  760. call_clear_on_leave scope_guard(this);
  761. internal_copy(table);
  762. scope_guard.dismiss();
  763. }
  764. concurrent_hash_map( const concurrent_hash_map &table, const allocator_type &a)
  765. : internal::hash_map_base(), my_allocator(a)
  766. {
  767. call_clear_on_leave scope_guard(this);
  768. internal_copy(table);
  769. scope_guard.dismiss();
  770. }
  771. #if __TBB_CPP11_RVALUE_REF_PRESENT
  772. //! Move constructor
  773. concurrent_hash_map( concurrent_hash_map &&table )
  774. : internal::hash_map_base(), my_allocator(std::move(table.get_allocator()))
  775. {
  776. internal_move(std::move(table));
  777. }
  778. //! Move constructor
  779. concurrent_hash_map( concurrent_hash_map &&table, const allocator_type &a )
  780. : internal::hash_map_base(), my_allocator(a)
  781. {
  782. if (a == table.get_allocator()){
  783. internal_move(std::move(table));
  784. }else{
  785. call_clear_on_leave scope_guard(this);
  786. internal_copy(std::make_move_iterator(table.begin()), std::make_move_iterator(table.end()), table.size());
  787. scope_guard.dismiss();
  788. }
  789. }
  790. #endif //__TBB_CPP11_RVALUE_REF_PRESENT
  791. //! Construction with copying iteration range and given allocator instance
  792. template<typename I>
  793. concurrent_hash_map( I first, I last, const allocator_type &a = allocator_type() )
  794. : internal::hash_map_base(), my_allocator(a)
  795. {
  796. call_clear_on_leave scope_guard(this);
  797. internal_copy(first, last, std::distance(first, last));
  798. scope_guard.dismiss();
  799. }
  800. template<typename I>
  801. concurrent_hash_map( I first, I last, const HashCompare& compare, const allocator_type& a = allocator_type() )
  802. : internal::hash_map_base(), my_allocator(a), my_hash_compare(compare)
  803. {
  804. call_clear_on_leave scope_guard(this);
  805. internal_copy(first, last, std::distance(first, last));
  806. scope_guard.dismiss();
  807. }
  808. #if __TBB_INITIALIZER_LISTS_PRESENT
  809. //! Construct empty table with n preallocated buckets. This number serves also as initial concurrency level.
  810. concurrent_hash_map( std::initializer_list<value_type> il, const allocator_type &a = allocator_type() )
  811. : internal::hash_map_base(), my_allocator(a)
  812. {
  813. call_clear_on_leave scope_guard(this);
  814. internal_copy(il.begin(), il.end(), il.size());
  815. scope_guard.dismiss();
  816. }
  817. concurrent_hash_map( std::initializer_list<value_type> il, const HashCompare& compare, const allocator_type& a = allocator_type() )
  818. : internal::hash_map_base(), my_allocator(a), my_hash_compare(compare)
  819. {
  820. call_clear_on_leave scope_guard(this);
  821. internal_copy(il.begin(), il.end(), il.size());
  822. scope_guard.dismiss();
  823. }
  824. #endif //__TBB_INITIALIZER_LISTS_PRESENT
  825. //! Assignment
  826. concurrent_hash_map& operator=( const concurrent_hash_map &table ) {
  827. if( this!=&table ) {
  828. typedef typename node_allocator_traits::propagate_on_container_copy_assignment pocca_type;
  829. clear();
  830. tbb::internal::allocator_copy_assignment(my_allocator, table.my_allocator, pocca_type());
  831. internal_copy(table);
  832. }
  833. return *this;
  834. }
  835. #if __TBB_CPP11_RVALUE_REF_PRESENT
  836. //! Move Assignment
  837. concurrent_hash_map& operator=( concurrent_hash_map &&table ) {
  838. if(this != &table) {
  839. typedef typename node_allocator_traits::propagate_on_container_move_assignment pocma_type;
  840. internal_move_assign(std::move(table), pocma_type());
  841. }
  842. return *this;
  843. }
  844. #endif //__TBB_CPP11_RVALUE_REF_PRESENT
  845. #if __TBB_INITIALIZER_LISTS_PRESENT
  846. //! Assignment
  847. concurrent_hash_map& operator=( std::initializer_list<value_type> il ) {
  848. clear();
  849. internal_copy(il.begin(), il.end(), il.size());
  850. return *this;
  851. }
  852. #endif //__TBB_INITIALIZER_LISTS_PRESENT
  853. //! Rehashes and optionally resizes the whole table.
  854. /** Useful to optimize performance before or after concurrent operations.
  855. Also enables using of find() and count() concurrent methods in serial context. */
  856. void rehash(size_type n = 0);
  857. //! Clear table
  858. void clear();
  859. //! Clear table and destroy it.
  860. ~concurrent_hash_map() { clear(); }
  861. //------------------------------------------------------------------------
  862. // Parallel algorithm support
  863. //------------------------------------------------------------------------
  864. range_type range( size_type grainsize=1 ) {
  865. return range_type( *this, grainsize );
  866. }
  867. const_range_type range( size_type grainsize=1 ) const {
  868. return const_range_type( *this, grainsize );
  869. }
  870. //------------------------------------------------------------------------
  871. // STL support - not thread-safe methods
  872. //------------------------------------------------------------------------
  873. iterator begin() { return iterator( *this, 0, my_embedded_segment, my_embedded_segment->node_list ); }
  874. iterator end() { return iterator( *this, 0, 0, 0 ); }
  875. const_iterator begin() const { return const_iterator( *this, 0, my_embedded_segment, my_embedded_segment->node_list ); }
  876. const_iterator end() const { return const_iterator( *this, 0, 0, 0 ); }
  877. std::pair<iterator, iterator> equal_range( const Key& key ) { return internal_equal_range( key, end() ); }
  878. std::pair<const_iterator, const_iterator> equal_range( const Key& key ) const { return internal_equal_range( key, end() ); }
  879. //! Number of items in table.
  880. size_type size() const { return my_size; }
  881. //! True if size()==0.
  882. bool empty() const { return my_size == 0; }
  883. //! Upper bound on size.
  884. size_type max_size() const {return (~size_type(0))/sizeof(node);}
  885. //! Returns the current number of buckets
  886. size_type bucket_count() const { return my_mask+1; }
  887. //! return allocator object
  888. allocator_type get_allocator() const { return this->my_allocator; }
  889. //! swap two instances. Iterators are invalidated
  890. void swap( concurrent_hash_map &table );
  891. //------------------------------------------------------------------------
  892. // concurrent map operations
  893. //------------------------------------------------------------------------
  894. //! Return count of items (0 or 1)
  895. size_type count( const Key &key ) const {
  896. return const_cast<concurrent_hash_map*>(this)->lookup(/*insert*/false, key, NULL, NULL, /*write=*/false, &do_not_allocate_node );
  897. }
  898. //! Find item and acquire a read lock on the item.
  899. /** Return true if item is found, false otherwise. */
  900. bool find( const_accessor &result, const Key &key ) const {
  901. result.release();
  902. return const_cast<concurrent_hash_map*>(this)->lookup(/*insert*/false, key, NULL, &result, /*write=*/false, &do_not_allocate_node );
  903. }
  904. //! Find item and acquire a write lock on the item.
  905. /** Return true if item is found, false otherwise. */
  906. bool find( accessor &result, const Key &key ) {
  907. result.release();
  908. return lookup(/*insert*/false, key, NULL, &result, /*write=*/true, &do_not_allocate_node );
  909. }
  910. //! Insert item (if not already present) and acquire a read lock on the item.
  911. /** Returns true if item is new. */
  912. bool insert( const_accessor &result, const Key &key ) {
  913. result.release();
  914. return lookup(/*insert*/true, key, NULL, &result, /*write=*/false, &allocate_node_default_construct );
  915. }
  916. //! Insert item (if not already present) and acquire a write lock on the item.
  917. /** Returns true if item is new. */
  918. bool insert( accessor &result, const Key &key ) {
  919. result.release();
  920. return lookup(/*insert*/true, key, NULL, &result, /*write=*/true, &allocate_node_default_construct );
  921. }
  922. //! Insert item by copying if there is no such key present already and acquire a read lock on the item.
  923. /** Returns true if item is new. */
  924. bool insert( const_accessor &result, const value_type &value ) {
  925. result.release();
  926. return lookup(/*insert*/true, value.first, &value.second, &result, /*write=*/false, &allocate_node_copy_construct );
  927. }
  928. //! Insert item by copying if there is no such key present already and acquire a write lock on the item.
  929. /** Returns true if item is new. */
  930. bool insert( accessor &result, const value_type &value ) {
  931. result.release();
  932. return lookup(/*insert*/true, value.first, &value.second, &result, /*write=*/true, &allocate_node_copy_construct );
  933. }
  934. //! Insert item by copying if there is no such key present already
  935. /** Returns true if item is inserted. */
  936. bool insert( const value_type &value ) {
  937. return lookup(/*insert*/true, value.first, &value.second, NULL, /*write=*/false, &allocate_node_copy_construct );
  938. }
  939. #if __TBB_CPP11_RVALUE_REF_PRESENT
  940. //! Insert item by copying if there is no such key present already and acquire a read lock on the item.
  941. /** Returns true if item is new. */
  942. bool insert( const_accessor &result, value_type && value ) {
  943. return generic_move_insert(result, std::move(value));
  944. }
  945. //! Insert item by copying if there is no such key present already and acquire a write lock on the item.
  946. /** Returns true if item is new. */
  947. bool insert( accessor &result, value_type && value ) {
  948. return generic_move_insert(result, std::move(value));
  949. }
  950. //! Insert item by copying if there is no such key present already
  951. /** Returns true if item is inserted. */
  952. bool insert( value_type && value ) {
  953. return generic_move_insert(accessor_not_used(), std::move(value));
  954. }
  955. #if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  956. //! Insert item by copying if there is no such key present already and acquire a read lock on the item.
  957. /** Returns true if item is new. */
  958. template<typename... Args>
  959. bool emplace( const_accessor &result, Args&&... args ) {
  960. return generic_emplace(result, std::forward<Args>(args)...);
  961. }
  962. //! Insert item by copying if there is no such key present already and acquire a write lock on the item.
  963. /** Returns true if item is new. */
  964. template<typename... Args>
  965. bool emplace( accessor &result, Args&&... args ) {
  966. return generic_emplace(result, std::forward<Args>(args)...);
  967. }
  968. //! Insert item by copying if there is no such key present already
  969. /** Returns true if item is inserted. */
  970. template<typename... Args>
  971. bool emplace( Args&&... args ) {
  972. return generic_emplace(accessor_not_used(), std::forward<Args>(args)...);
  973. }
  974. #endif //__TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  975. #endif //__TBB_CPP11_RVALUE_REF_PRESENT
  976. //! Insert range [first, last)
  977. template<typename I>
  978. void insert( I first, I last ) {
  979. for ( ; first != last; ++first )
  980. insert( *first );
  981. }
  982. #if __TBB_INITIALIZER_LISTS_PRESENT
  983. //! Insert initializer list
  984. void insert( std::initializer_list<value_type> il ) {
  985. insert( il.begin(), il.end() );
  986. }
  987. #endif //__TBB_INITIALIZER_LISTS_PRESENT
  988. //! Erase item.
  989. /** Return true if item was erased by particularly this call. */
  990. bool erase( const Key& key );
  991. //! Erase item by const_accessor.
  992. /** Return true if item was erased by particularly this call. */
  993. bool erase( const_accessor& item_accessor ) {
  994. return exclude( item_accessor );
  995. }
  996. //! Erase item by accessor.
  997. /** Return true if item was erased by particularly this call. */
  998. bool erase( accessor& item_accessor ) {
  999. return exclude( item_accessor );
  1000. }
  1001. protected:
  1002. //! Insert or find item and optionally acquire a lock on the item.
  1003. bool lookup(bool op_insert, const Key &key, const T *t, const_accessor *result, bool write, node* (*allocate_node)(node_allocator_type& , const Key &, const T * ), node *tmp_n = 0 ) ;
  1004. struct accessor_not_used { void release(){}};
  1005. friend const_accessor* accessor_location( accessor_not_used const& ){ return NULL;}
  1006. friend const_accessor* accessor_location( const_accessor & a ) { return &a;}
  1007. friend bool is_write_access_needed( accessor const& ) { return true;}
  1008. friend bool is_write_access_needed( const_accessor const& ) { return false;}
  1009. friend bool is_write_access_needed( accessor_not_used const& ) { return false;}
  1010. #if __TBB_CPP11_RVALUE_REF_PRESENT
  1011. template<typename Accessor>
  1012. bool generic_move_insert( Accessor && result, value_type && value ) {
  1013. result.release();
  1014. return lookup(/*insert*/true, value.first, &value.second, accessor_location(result), is_write_access_needed(result), &allocate_node_move_construct );
  1015. }
  1016. #if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  1017. template<typename Accessor, typename... Args>
  1018. bool generic_emplace( Accessor && result, Args &&... args ) {
  1019. result.release();
  1020. node * node_ptr = create_node(my_allocator, std::forward<Args>(args)...);
  1021. return lookup(/*insert*/true, node_ptr->value().first, NULL, accessor_location(result), is_write_access_needed(result), &do_not_allocate_node, node_ptr );
  1022. }
  1023. #endif //__TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
  1024. #endif //__TBB_CPP11_RVALUE_REF_PRESENT
  1025. //! delete item by accessor
  1026. bool exclude( const_accessor &item_accessor );
  1027. //! Returns an iterator for an item defined by the key, or for the next item after it (if upper==true)
  1028. template<typename I>
  1029. std::pair<I, I> internal_equal_range( const Key& key, I end ) const;
  1030. //! Copy "source" to *this, where *this must start out empty.
  1031. void internal_copy( const concurrent_hash_map& source );
  1032. template<typename I>
  1033. void internal_copy( I first, I last, size_type reserve_size );
  1034. #if __TBB_CPP11_RVALUE_REF_PRESENT
  1035. // A compile-time dispatch to allow move assignment of containers with non-movable value_type if POCMA is true_type
  1036. void internal_move_assign(concurrent_hash_map&& other, tbb::internal::traits_true_type) {
  1037. tbb::internal::allocator_move_assignment(my_allocator, other.my_allocator, tbb::internal::traits_true_type());
  1038. internal_move(std::move(other));
  1039. }
  1040. void internal_move_assign(concurrent_hash_map&& other, tbb::internal::traits_false_type) {
  1041. if (this->my_allocator == other.my_allocator) {
  1042. internal_move(std::move(other));
  1043. } else {
  1044. //do per element move
  1045. internal_copy(std::make_move_iterator(other.begin()), std::make_move_iterator(other.end()), other.size());
  1046. }
  1047. }
  1048. #endif
  1049. //! Fast find when no concurrent erasure is used. For internal use inside TBB only!
  1050. /** Return pointer to item with given key, or NULL if no such item exists.
  1051. Must not be called concurrently with erasure operations. */
  1052. const_pointer internal_fast_find( const Key& key ) const {
  1053. hashcode_t h = my_hash_compare.hash( key );
  1054. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  1055. node *n;
  1056. restart:
  1057. __TBB_ASSERT((m&(m+1))==0, "data structure is invalid");
  1058. bucket *b = get_bucket( h & m );
  1059. // TODO: actually, notification is unnecessary here, just hiding double-check
  1060. if( itt_load_word_with_acquire(b->node_list) == internal::rehash_req )
  1061. {
  1062. bucket::scoped_t lock;
  1063. if( lock.try_acquire( b->mutex, /*write=*/true ) ) {
  1064. if( b->node_list == internal::rehash_req)
  1065. const_cast<concurrent_hash_map*>(this)->rehash_bucket( b, h & m ); //recursive rehashing
  1066. }
  1067. else lock.acquire( b->mutex, /*write=*/false );
  1068. __TBB_ASSERT(b->node_list!=internal::rehash_req,NULL);
  1069. }
  1070. n = search_bucket( key, b );
  1071. if( n )
  1072. return n->storage();
  1073. else if( check_mask_race( h, m ) )
  1074. goto restart;
  1075. return 0;
  1076. }
  1077. };
  1078. #if __TBB_CPP17_DEDUCTION_GUIDES_PRESENT
  1079. namespace internal {
  1080. using namespace tbb::internal;
  1081. template<template<typename...> typename Map, typename Key, typename T, typename... Args>
  1082. using hash_map_t = Map<
  1083. Key, T,
  1084. std::conditional_t< (sizeof...(Args)>0) && !is_allocator_v< pack_element_t<0, Args...> >,
  1085. pack_element_t<0, Args...>, tbb_hash_compare<Key> >,
  1086. std::conditional_t< (sizeof...(Args)>0) && is_allocator_v< pack_element_t<sizeof...(Args)-1, Args...> >,
  1087. pack_element_t<sizeof...(Args)-1, Args...>, tbb_allocator<std::pair<const Key, T> > >
  1088. >;
  1089. }
  1090. // Deduction guide for the constructor from two iterators and hash_compare/ allocator
  1091. template<typename I, typename... Args>
  1092. concurrent_hash_map(I, I, Args...)
  1093. -> internal::hash_map_t<concurrent_hash_map, internal::iterator_key_t<I>,internal::iterator_mapped_t<I>, Args...>;
  1094. // Deduction guide for the constructor from an initializer_list and hash_compare/ allocator
  1095. // Deduction guide for an initializer_list, hash_compare and allocator is implicit
  1096. template<typename Key, typename T, typename CompareOrAllocator>
  1097. concurrent_hash_map(std::initializer_list<std::pair<const Key, T>>, CompareOrAllocator)
  1098. -> internal::hash_map_t<concurrent_hash_map, Key, T, CompareOrAllocator>;
  1099. #endif /* __TBB_CPP17_DEDUCTION_GUIDES_PRESENT */
  1100. template<typename Key, typename T, typename HashCompare, typename A>
  1101. bool concurrent_hash_map<Key,T,HashCompare,A>::lookup( bool op_insert, const Key &key, const T *t, const_accessor *result, bool write, node* (*allocate_node)(node_allocator_type& , const Key&, const T*), node *tmp_n ) {
  1102. __TBB_ASSERT( !result || !result->my_node, NULL );
  1103. bool return_value;
  1104. hashcode_t const h = my_hash_compare.hash( key );
  1105. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  1106. segment_index_t grow_segment = 0;
  1107. node *n;
  1108. restart:
  1109. {//lock scope
  1110. __TBB_ASSERT((m&(m+1))==0, "data structure is invalid");
  1111. return_value = false;
  1112. // get bucket
  1113. bucket_accessor b( this, h & m );
  1114. // find a node
  1115. n = search_bucket( key, b() );
  1116. if( op_insert ) {
  1117. // [opt] insert a key
  1118. if( !n ) {
  1119. if( !tmp_n ) {
  1120. tmp_n = allocate_node(my_allocator, key, t);
  1121. }
  1122. if( !b.is_writer() && !b.upgrade_to_writer() ) { // TODO: improved insertion
  1123. // Rerun search_list, in case another thread inserted the item during the upgrade.
  1124. n = search_bucket( key, b() );
  1125. if( is_valid(n) ) { // unfortunately, it did
  1126. b.downgrade_to_reader();
  1127. goto exists;
  1128. }
  1129. }
  1130. if( check_mask_race(h, m) )
  1131. goto restart; // b.release() is done in ~b().
  1132. // insert and set flag to grow the container
  1133. grow_segment = insert_new_node( b(), n = tmp_n, m );
  1134. tmp_n = 0;
  1135. return_value = true;
  1136. }
  1137. } else { // find or count
  1138. if( !n ) {
  1139. if( check_mask_race( h, m ) )
  1140. goto restart; // b.release() is done in ~b(). TODO: replace by continue
  1141. return false;
  1142. }
  1143. return_value = true;
  1144. }
  1145. exists:
  1146. if( !result ) goto check_growth;
  1147. // TODO: the following seems as generic/regular operation
  1148. // acquire the item
  1149. if( !result->try_acquire( n->mutex, write ) ) {
  1150. for( tbb::internal::atomic_backoff backoff(true);; ) {
  1151. if( result->try_acquire( n->mutex, write ) ) break;
  1152. if( !backoff.bounded_pause() ) {
  1153. // the wait takes really long, restart the operation
  1154. b.release();
  1155. __TBB_ASSERT( !op_insert || !return_value, "Can't acquire new item in locked bucket?" );
  1156. __TBB_Yield();
  1157. m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  1158. goto restart;
  1159. }
  1160. }
  1161. }
  1162. }//lock scope
  1163. result->my_node = n;
  1164. result->my_hash = h;
  1165. check_growth:
  1166. // [opt] grow the container
  1167. if( grow_segment ) {
  1168. #if __TBB_STATISTICS
  1169. my_info_resizes++; // concurrent ones
  1170. #endif
  1171. enable_segment( grow_segment, my_allocator );
  1172. }
  1173. if( tmp_n ) // if op_insert only
  1174. delete_node( tmp_n );
  1175. return return_value;
  1176. }
  1177. template<typename Key, typename T, typename HashCompare, typename A>
  1178. template<typename I>
  1179. std::pair<I, I> concurrent_hash_map<Key,T,HashCompare,A>::internal_equal_range( const Key& key, I end_ ) const {
  1180. hashcode_t h = my_hash_compare.hash( key );
  1181. hashcode_t m = my_mask;
  1182. __TBB_ASSERT((m&(m+1))==0, "data structure is invalid");
  1183. h &= m;
  1184. bucket *b = get_bucket( h );
  1185. while( b->node_list == internal::rehash_req ) {
  1186. m = ( 1u<<__TBB_Log2( h ) ) - 1; // get parent mask from the topmost bit
  1187. b = get_bucket( h &= m );
  1188. }
  1189. node *n = search_bucket( key, b );
  1190. if( !n )
  1191. return std::make_pair(end_, end_);
  1192. iterator lower(*this, h, b, n), upper(lower);
  1193. return std::make_pair(lower, ++upper);
  1194. }
  1195. template<typename Key, typename T, typename HashCompare, typename A>
  1196. bool concurrent_hash_map<Key,T,HashCompare,A>::exclude( const_accessor &item_accessor ) {
  1197. __TBB_ASSERT( item_accessor.my_node, NULL );
  1198. node_base *const n = item_accessor.my_node;
  1199. hashcode_t const h = item_accessor.my_hash;
  1200. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  1201. do {
  1202. // get bucket
  1203. bucket_accessor b( this, h & m, /*writer=*/true );
  1204. node_base **p = &b()->node_list;
  1205. while( *p && *p != n )
  1206. p = &(*p)->next;
  1207. if( !*p ) { // someone else was first
  1208. if( check_mask_race( h, m ) )
  1209. continue;
  1210. item_accessor.release();
  1211. return false;
  1212. }
  1213. __TBB_ASSERT( *p == n, NULL );
  1214. *p = n->next; // remove from container
  1215. my_size--;
  1216. break;
  1217. } while(true);
  1218. if( !item_accessor.is_writer() ) // need to get exclusive lock
  1219. item_accessor.upgrade_to_writer(); // return value means nothing here
  1220. item_accessor.release();
  1221. delete_node( n ); // Only one thread can delete it
  1222. return true;
  1223. }
  1224. template<typename Key, typename T, typename HashCompare, typename A>
  1225. bool concurrent_hash_map<Key,T,HashCompare,A>::erase( const Key &key ) {
  1226. node_base *n;
  1227. hashcode_t const h = my_hash_compare.hash( key );
  1228. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  1229. restart:
  1230. {//lock scope
  1231. // get bucket
  1232. bucket_accessor b( this, h & m );
  1233. search:
  1234. node_base **p = &b()->node_list;
  1235. n = *p;
  1236. while( is_valid(n) && !my_hash_compare.equal(key, static_cast<node*>(n)->value().first ) ) {
  1237. p = &n->next;
  1238. n = *p;
  1239. }
  1240. if( !n ) { // not found, but mask could be changed
  1241. if( check_mask_race( h, m ) )
  1242. goto restart;
  1243. return false;
  1244. }
  1245. else if( !b.is_writer() && !b.upgrade_to_writer() ) {
  1246. if( check_mask_race( h, m ) ) // contended upgrade, check mask
  1247. goto restart;
  1248. goto search;
  1249. }
  1250. *p = n->next;
  1251. my_size--;
  1252. }
  1253. {
  1254. typename node::scoped_t item_locker( n->mutex, /*write=*/true );
  1255. }
  1256. // note: there should be no threads pretending to acquire this mutex again, do not try to upgrade const_accessor!
  1257. delete_node( n ); // Only one thread can delete it due to write lock on the bucket
  1258. return true;
  1259. }
  1260. template<typename Key, typename T, typename HashCompare, typename A>
  1261. void concurrent_hash_map<Key,T,HashCompare,A>::swap(concurrent_hash_map<Key,T,HashCompare,A> &table) {
  1262. typedef typename node_allocator_traits::propagate_on_container_swap pocs_type;
  1263. if (this != &table && (pocs_type::value || my_allocator == table.my_allocator)) {
  1264. using std::swap;
  1265. tbb::internal::allocator_swap(this->my_allocator, table.my_allocator, pocs_type());
  1266. swap(this->my_hash_compare, table.my_hash_compare);
  1267. internal_swap(table);
  1268. }
  1269. }
  1270. template<typename Key, typename T, typename HashCompare, typename A>
  1271. void concurrent_hash_map<Key,T,HashCompare,A>::rehash(size_type sz) {
  1272. reserve( sz, my_allocator ); // TODO: add reduction of number of buckets as well
  1273. hashcode_t mask = my_mask;
  1274. hashcode_t b = (mask+1)>>1; // size or first index of the last segment
  1275. __TBB_ASSERT((b&(b-1))==0, NULL); // zero or power of 2
  1276. bucket *bp = get_bucket( b ); // only the last segment should be scanned for rehashing
  1277. for(; b <= mask; b++, bp++ ) {
  1278. node_base *n = bp->node_list;
  1279. __TBB_ASSERT( is_valid(n) || n == internal::empty_rehashed || n == internal::rehash_req, "Broken internal structure" );
  1280. __TBB_ASSERT( *reinterpret_cast<intptr_t*>(&bp->mutex) == 0, "concurrent or unexpectedly terminated operation during rehash() execution" );
  1281. if( n == internal::rehash_req ) { // rehash bucket, conditional because rehashing of a previous bucket may affect this one
  1282. hashcode_t h = b; bucket *b_old = bp;
  1283. do {
  1284. __TBB_ASSERT( h > 1, "The lowermost buckets can't be rehashed" );
  1285. hashcode_t m = ( 1u<<__TBB_Log2( h ) ) - 1; // get parent mask from the topmost bit
  1286. b_old = get_bucket( h &= m );
  1287. } while( b_old->node_list == internal::rehash_req );
  1288. // now h - is index of the root rehashed bucket b_old
  1289. mark_rehashed_levels( h ); // mark all non-rehashed children recursively across all segments
  1290. for( node_base **p = &b_old->node_list, *q = *p; is_valid(q); q = *p ) {
  1291. hashcode_t c = my_hash_compare.hash( static_cast<node*>(q)->value().first );
  1292. if( (c & mask) != h ) { // should be rehashed
  1293. *p = q->next; // exclude from b_old
  1294. bucket *b_new = get_bucket( c & mask );
  1295. __TBB_ASSERT( b_new->node_list != internal::rehash_req, "hash() function changed for key in table or internal error" );
  1296. add_to_bucket( b_new, q );
  1297. } else p = &q->next; // iterate to next item
  1298. }
  1299. }
  1300. }
  1301. #if TBB_USE_PERFORMANCE_WARNINGS
  1302. int current_size = int(my_size), buckets = int(mask)+1, empty_buckets = 0, overpopulated_buckets = 0; // usage statistics
  1303. static bool reported = false;
  1304. #endif
  1305. #if TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS
  1306. for( b = 0; b <= mask; b++ ) {// only last segment should be scanned for rehashing
  1307. if( b & (b-2) ) ++bp; // not the beginning of a segment
  1308. else bp = get_bucket( b );
  1309. node_base *n = bp->node_list;
  1310. __TBB_ASSERT( *reinterpret_cast<intptr_t*>(&bp->mutex) == 0, "concurrent or unexpectedly terminated operation during rehash() execution" );
  1311. __TBB_ASSERT( is_valid(n) || n == internal::empty_rehashed, "Broken internal structure" );
  1312. #if TBB_USE_PERFORMANCE_WARNINGS
  1313. if( n == internal::empty_rehashed ) empty_buckets++;
  1314. else if( n->next ) overpopulated_buckets++;
  1315. #endif
  1316. #if TBB_USE_ASSERT
  1317. for( ; is_valid(n); n = n->next ) {
  1318. hashcode_t h = my_hash_compare.hash( static_cast<node*>(n)->value().first ) & mask;
  1319. __TBB_ASSERT( h == b, "hash() function changed for key in table or internal error" );
  1320. }
  1321. #endif
  1322. }
  1323. #endif // TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS
  1324. #if TBB_USE_PERFORMANCE_WARNINGS
  1325. if( buckets > current_size) empty_buckets -= buckets - current_size;
  1326. else overpopulated_buckets -= current_size - buckets; // TODO: load_factor?
  1327. if( !reported && buckets >= 512 && ( 2*empty_buckets > current_size || 2*overpopulated_buckets > current_size ) ) {
  1328. tbb::internal::runtime_warning(
  1329. "Performance is not optimal because the hash function produces bad randomness in lower bits in %s.\nSize: %d Empties: %d Overlaps: %d",
  1330. #if __TBB_USE_OPTIONAL_RTTI
  1331. typeid(*this).name(),
  1332. #else
  1333. "concurrent_hash_map",
  1334. #endif
  1335. current_size, empty_buckets, overpopulated_buckets );
  1336. reported = true;
  1337. }
  1338. #endif
  1339. }
  1340. template<typename Key, typename T, typename HashCompare, typename A>
  1341. void concurrent_hash_map<Key,T,HashCompare,A>::clear() {
  1342. hashcode_t m = my_mask;
  1343. __TBB_ASSERT((m&(m+1))==0, "data structure is invalid");
  1344. #if TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1345. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1346. int current_size = int(my_size), buckets = int(m)+1, empty_buckets = 0, overpopulated_buckets = 0; // usage statistics
  1347. static bool reported = false;
  1348. #endif
  1349. bucket *bp = 0;
  1350. // check consistency
  1351. for( segment_index_t b = 0; b <= m; b++ ) {
  1352. if( b & (b-2) ) ++bp; // not the beginning of a segment
  1353. else bp = get_bucket( b );
  1354. node_base *n = bp->node_list;
  1355. __TBB_ASSERT( is_valid(n) || n == internal::empty_rehashed || n == internal::rehash_req, "Broken internal structure" );
  1356. __TBB_ASSERT( *reinterpret_cast<intptr_t*>(&bp->mutex) == 0, "concurrent or unexpectedly terminated operation during clear() execution" );
  1357. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1358. if( n == internal::empty_rehashed ) empty_buckets++;
  1359. else if( n == internal::rehash_req ) buckets--;
  1360. else if( n->next ) overpopulated_buckets++;
  1361. #endif
  1362. #if __TBB_EXTRA_DEBUG
  1363. for(; is_valid(n); n = n->next ) {
  1364. hashcode_t h = my_hash_compare.hash( static_cast<node*>(n)->value().first );
  1365. h &= m;
  1366. __TBB_ASSERT( h == b || get_bucket(h)->node_list == internal::rehash_req, "hash() function changed for key in table or internal error" );
  1367. }
  1368. #endif
  1369. }
  1370. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1371. #if __TBB_STATISTICS
  1372. printf( "items=%d buckets: capacity=%d rehashed=%d empty=%d overpopulated=%d"
  1373. " concurrent: resizes=%u rehashes=%u restarts=%u\n",
  1374. current_size, int(m+1), buckets, empty_buckets, overpopulated_buckets,
  1375. unsigned(my_info_resizes), unsigned(my_info_rehashes), unsigned(my_info_restarts) );
  1376. my_info_resizes = 0; // concurrent ones
  1377. my_info_restarts = 0; // race collisions
  1378. my_info_rehashes = 0; // invocations of rehash_bucket
  1379. #endif
  1380. if( buckets > current_size) empty_buckets -= buckets - current_size;
  1381. else overpopulated_buckets -= current_size - buckets; // TODO: load_factor?
  1382. if( !reported && buckets >= 512 && ( 2*empty_buckets > current_size || 2*overpopulated_buckets > current_size ) ) {
  1383. tbb::internal::runtime_warning(
  1384. "Performance is not optimal because the hash function produces bad randomness in lower bits in %s.\nSize: %d Empties: %d Overlaps: %d",
  1385. #if __TBB_USE_OPTIONAL_RTTI
  1386. typeid(*this).name(),
  1387. #else
  1388. "concurrent_hash_map",
  1389. #endif
  1390. current_size, empty_buckets, overpopulated_buckets );
  1391. reported = true;
  1392. }
  1393. #endif
  1394. #endif // TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1395. my_size = 0;
  1396. segment_index_t s = segment_index_of( m );
  1397. __TBB_ASSERT( s+1 == pointers_per_table || !my_table[s+1], "wrong mask or concurrent grow" );
  1398. do {
  1399. __TBB_ASSERT( is_valid( my_table[s] ), "wrong mask or concurrent grow" );
  1400. segment_ptr_t buckets_ptr = my_table[s];
  1401. size_type sz = segment_size( s ? s : 1 );
  1402. for( segment_index_t i = 0; i < sz; i++ )
  1403. for( node_base *n = buckets_ptr[i].node_list; is_valid(n); n = buckets_ptr[i].node_list ) {
  1404. buckets_ptr[i].node_list = n->next;
  1405. delete_node( n );
  1406. }
  1407. delete_segment(s, my_allocator);
  1408. } while(s-- > 0);
  1409. my_mask = embedded_buckets - 1;
  1410. }
  1411. template<typename Key, typename T, typename HashCompare, typename A>
  1412. void concurrent_hash_map<Key,T,HashCompare,A>::internal_copy( const concurrent_hash_map& source ) {
  1413. hashcode_t mask = source.my_mask;
  1414. if( my_mask == mask ) { // optimized version
  1415. reserve( source.my_size, my_allocator ); // TODO: load_factor?
  1416. bucket *dst = 0, *src = 0;
  1417. bool rehash_required = false;
  1418. for( hashcode_t k = 0; k <= mask; k++ ) {
  1419. if( k & (k-2) ) ++dst,src++; // not the beginning of a segment
  1420. else { dst = get_bucket( k ); src = source.get_bucket( k ); }
  1421. __TBB_ASSERT( dst->node_list != internal::rehash_req, "Invalid bucket in destination table");
  1422. node *n = static_cast<node*>( src->node_list );
  1423. if( n == internal::rehash_req ) { // source is not rehashed, items are in previous buckets
  1424. rehash_required = true;
  1425. dst->node_list = internal::rehash_req;
  1426. } else for(; n; n = static_cast<node*>( n->next ) ) {
  1427. node* node_ptr = create_node(my_allocator, n->value().first, n->value().second);
  1428. add_to_bucket( dst, node_ptr);
  1429. ++my_size; // TODO: replace by non-atomic op
  1430. }
  1431. }
  1432. if( rehash_required ) rehash();
  1433. } else internal_copy( source.begin(), source.end(), source.my_size );
  1434. }
  1435. template<typename Key, typename T, typename HashCompare, typename A>
  1436. template<typename I>
  1437. void concurrent_hash_map<Key,T,HashCompare,A>::internal_copy(I first, I last, size_type reserve_size) {
  1438. reserve( reserve_size, my_allocator ); // TODO: load_factor?
  1439. hashcode_t m = my_mask;
  1440. for(; first != last; ++first) {
  1441. hashcode_t h = my_hash_compare.hash( (*first).first );
  1442. bucket *b = get_bucket( h & m );
  1443. __TBB_ASSERT( b->node_list != internal::rehash_req, "Invalid bucket in destination table");
  1444. node* node_ptr = create_node(my_allocator, (*first).first, (*first).second);
  1445. add_to_bucket( b, node_ptr );
  1446. ++my_size; // TODO: replace by non-atomic op
  1447. }
  1448. }
  1449. } // namespace interface5
  1450. using interface5::concurrent_hash_map;
  1451. template<typename Key, typename T, typename HashCompare, typename A1, typename A2>
  1452. inline bool operator==(const concurrent_hash_map<Key, T, HashCompare, A1> &a, const concurrent_hash_map<Key, T, HashCompare, A2> &b) {
  1453. if(a.size() != b.size()) return false;
  1454. typename concurrent_hash_map<Key, T, HashCompare, A1>::const_iterator i(a.begin()), i_end(a.end());
  1455. typename concurrent_hash_map<Key, T, HashCompare, A2>::const_iterator j, j_end(b.end());
  1456. for(; i != i_end; ++i) {
  1457. j = b.equal_range(i->first).first;
  1458. if( j == j_end || !(i->second == j->second) ) return false;
  1459. }
  1460. return true;
  1461. }
  1462. template<typename Key, typename T, typename HashCompare, typename A1, typename A2>
  1463. inline bool operator!=(const concurrent_hash_map<Key, T, HashCompare, A1> &a, const concurrent_hash_map<Key, T, HashCompare, A2> &b)
  1464. { return !(a == b); }
  1465. template<typename Key, typename T, typename HashCompare, typename A>
  1466. inline void swap(concurrent_hash_map<Key, T, HashCompare, A> &a, concurrent_hash_map<Key, T, HashCompare, A> &b)
  1467. { a.swap( b ); }
  1468. #if _MSC_VER && !defined(__INTEL_COMPILER)
  1469. #pragma warning( pop )
  1470. #endif // warning 4127 is back
  1471. } // namespace tbb
  1472. #include "internal/_warning_suppress_disable_notice.h"
  1473. #undef __TBB_concurrent_hash_map_H_include_area
  1474. #endif /* __TBB_concurrent_hash_map_H */