concurrent_hash_map.h 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. /*
  2. Copyright 2005-2013 Intel Corporation. All Rights Reserved.
  3. This file is part of Threading Building Blocks.
  4. Threading Building Blocks is free software; you can redistribute it
  5. and/or modify it under the terms of the GNU General Public License
  6. version 2 as published by the Free Software Foundation.
  7. Threading Building Blocks is distributed in the hope that it will be
  8. useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  9. of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with Threading Building Blocks; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. As a special exception, you may use this file as part of a free software
  15. library without restriction. Specifically, if other files instantiate
  16. templates or use macros or inline functions from this file, or you compile
  17. this file and link it with other files to produce an executable, this
  18. file does not by itself cause the resulting executable to be covered by
  19. the GNU General Public License. This exception does not however
  20. invalidate any other reasons why the executable file might be covered by
  21. the GNU General Public License.
  22. */
  23. #ifndef __TBB_concurrent_hash_map_H
  24. #define __TBB_concurrent_hash_map_H
  25. #include "tbb_stddef.h"
  26. #if !TBB_USE_EXCEPTIONS && _MSC_VER
  27. // Suppress "C++ exception handler used, but unwind semantics are not enabled" warning in STL headers
  28. #pragma warning (push)
  29. #pragma warning (disable: 4530)
  30. #endif
  31. #include <iterator>
  32. #include <utility> // Need std::pair
  33. #include <cstring> // Need std::memset
  34. #if !TBB_USE_EXCEPTIONS && _MSC_VER
  35. #pragma warning (pop)
  36. #endif
  37. #include "cache_aligned_allocator.h"
  38. #include "tbb_allocator.h"
  39. #include "spin_rw_mutex.h"
  40. #include "atomic.h"
  41. #include "aligned_space.h"
  42. #include "tbb_exception.h"
  43. #include "tbb_profiling.h"
  44. #include "internal/_concurrent_unordered_impl.h" // Need tbb_hasher
  45. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  46. #include <typeinfo>
  47. #endif
  48. #if __TBB_STATISTICS
  49. #include <stdio.h>
  50. #endif
  51. namespace tbb {
  52. //! hash_compare that is default argument for concurrent_hash_map
  53. template<typename Key>
  54. struct tbb_hash_compare {
  55. static size_t hash( const Key& a ) { return tbb_hasher(a); }
  56. static bool equal( const Key& a, const Key& b ) { return a == b; }
  57. };
  58. namespace interface5 {
  59. template<typename Key, typename T, typename HashCompare = tbb_hash_compare<Key>, typename A = tbb_allocator<std::pair<Key, T> > >
  60. class concurrent_hash_map;
  61. //! @cond INTERNAL
  62. namespace internal {
  63. //! Type of a hash code.
  64. typedef size_t hashcode_t;
  65. //! Node base type
  66. struct hash_map_node_base : tbb::internal::no_copy {
  67. //! Mutex type
  68. typedef spin_rw_mutex mutex_t;
  69. //! Scoped lock type for mutex
  70. typedef mutex_t::scoped_lock scoped_t;
  71. //! Next node in chain
  72. hash_map_node_base *next;
  73. mutex_t mutex;
  74. };
  75. //! Incompleteness flag value
  76. static hash_map_node_base *const rehash_req = reinterpret_cast<hash_map_node_base*>(size_t(3));
  77. //! Rehashed empty bucket flag
  78. static hash_map_node_base *const empty_rehashed = reinterpret_cast<hash_map_node_base*>(size_t(0));
  79. //! base class of concurrent_hash_map
  80. class hash_map_base {
  81. public:
  82. //! Size type
  83. typedef size_t size_type;
  84. //! Type of a hash code.
  85. typedef size_t hashcode_t;
  86. //! Segment index type
  87. typedef size_t segment_index_t;
  88. //! Node base type
  89. typedef hash_map_node_base node_base;
  90. //! Bucket type
  91. struct bucket : tbb::internal::no_copy {
  92. //! Mutex type for buckets
  93. typedef spin_rw_mutex mutex_t;
  94. //! Scoped lock type for mutex
  95. typedef mutex_t::scoped_lock scoped_t;
  96. mutex_t mutex;
  97. node_base *node_list;
  98. };
  99. //! Count of segments in the first block
  100. static size_type const embedded_block = 1;
  101. //! Count of segments in the first block
  102. static size_type const embedded_buckets = 1<<embedded_block;
  103. //! Count of segments in the first block
  104. static size_type const first_block = 8; //including embedded_block. perfect with bucket size 16, so the allocations are power of 4096
  105. //! Size of a pointer / table size
  106. static size_type const pointers_per_table = sizeof(segment_index_t) * 8; // one segment per bit
  107. //! Segment pointer
  108. typedef bucket *segment_ptr_t;
  109. //! Segment pointers table type
  110. typedef segment_ptr_t segments_table_t[pointers_per_table];
  111. //! Hash mask = sum of allocated segment sizes - 1
  112. atomic<hashcode_t> my_mask;
  113. //! Segment pointers table. Also prevents false sharing between my_mask and my_size
  114. segments_table_t my_table;
  115. //! Size of container in stored items
  116. atomic<size_type> my_size; // It must be in separate cache line from my_mask due to performance effects
  117. //! Zero segment
  118. bucket my_embedded_segment[embedded_buckets];
  119. #if __TBB_STATISTICS
  120. atomic<unsigned> my_info_resizes; // concurrent ones
  121. mutable atomic<unsigned> my_info_restarts; // race collisions
  122. atomic<unsigned> my_info_rehashes; // invocations of rehash_bucket
  123. #endif
  124. //! Constructor
  125. hash_map_base() {
  126. std::memset( this, 0, pointers_per_table*sizeof(segment_ptr_t) // 32*4=128 or 64*8=512
  127. + sizeof(my_size) + sizeof(my_mask) // 4+4 or 8+8
  128. + embedded_buckets*sizeof(bucket) ); // n*8 or n*16
  129. for( size_type i = 0; i < embedded_block; i++ ) // fill the table
  130. my_table[i] = my_embedded_segment + segment_base(i);
  131. my_mask = embedded_buckets - 1;
  132. __TBB_ASSERT( embedded_block <= first_block, "The first block number must include embedded blocks");
  133. #if __TBB_STATISTICS
  134. my_info_resizes = 0; // concurrent ones
  135. my_info_restarts = 0; // race collisions
  136. my_info_rehashes = 0; // invocations of rehash_bucket
  137. #endif
  138. }
  139. //! @return segment index of given index in the array
  140. static segment_index_t segment_index_of( size_type index ) {
  141. return segment_index_t( __TBB_Log2( index|1 ) );
  142. }
  143. //! @return the first array index of given segment
  144. static segment_index_t segment_base( segment_index_t k ) {
  145. return (segment_index_t(1)<<k & ~segment_index_t(1));
  146. }
  147. //! @return segment size except for @arg k == 0
  148. static size_type segment_size( segment_index_t k ) {
  149. return size_type(1)<<k; // fake value for k==0
  150. }
  151. //! @return true if @arg ptr is valid pointer
  152. static bool is_valid( void *ptr ) {
  153. return reinterpret_cast<uintptr_t>(ptr) > uintptr_t(63);
  154. }
  155. //! Initialize buckets
  156. static void init_buckets( segment_ptr_t ptr, size_type sz, bool is_initial ) {
  157. if( is_initial ) std::memset(ptr, 0, sz*sizeof(bucket) );
  158. else for(size_type i = 0; i < sz; i++, ptr++) {
  159. *reinterpret_cast<intptr_t*>(&ptr->mutex) = 0;
  160. ptr->node_list = rehash_req;
  161. }
  162. }
  163. //! Add node @arg n to bucket @arg b
  164. static void add_to_bucket( bucket *b, node_base *n ) {
  165. __TBB_ASSERT(b->node_list != rehash_req, NULL);
  166. n->next = b->node_list;
  167. b->node_list = n; // its under lock and flag is set
  168. }
  169. //! Exception safety helper
  170. struct enable_segment_failsafe : tbb::internal::no_copy {
  171. segment_ptr_t *my_segment_ptr;
  172. enable_segment_failsafe(segments_table_t &table, segment_index_t k) : my_segment_ptr(&table[k]) {}
  173. ~enable_segment_failsafe() {
  174. if( my_segment_ptr ) *my_segment_ptr = 0; // indicate no allocation in progress
  175. }
  176. };
  177. //! Enable segment
  178. void enable_segment( segment_index_t k, bool is_initial = false ) {
  179. __TBB_ASSERT( k, "Zero segment must be embedded" );
  180. enable_segment_failsafe watchdog( my_table, k );
  181. cache_aligned_allocator<bucket> alloc;
  182. size_type sz;
  183. __TBB_ASSERT( !is_valid(my_table[k]), "Wrong concurrent assignment");
  184. if( k >= first_block ) {
  185. sz = segment_size( k );
  186. segment_ptr_t ptr = alloc.allocate( sz );
  187. init_buckets( ptr, sz, is_initial );
  188. itt_hide_store_word( my_table[k], ptr );
  189. sz <<= 1;// double it to get entire capacity of the container
  190. } else { // the first block
  191. __TBB_ASSERT( k == embedded_block, "Wrong segment index" );
  192. sz = segment_size( first_block );
  193. segment_ptr_t ptr = alloc.allocate( sz - embedded_buckets );
  194. init_buckets( ptr, sz - embedded_buckets, is_initial );
  195. ptr -= segment_base(embedded_block);
  196. for(segment_index_t i = embedded_block; i < first_block; i++) // calc the offsets
  197. itt_hide_store_word( my_table[i], ptr + segment_base(i) );
  198. }
  199. itt_store_word_with_release( my_mask, sz-1 );
  200. watchdog.my_segment_ptr = 0;
  201. }
  202. //! Get bucket by (masked) hashcode
  203. bucket *get_bucket( hashcode_t h ) const throw() { // TODO: add throw() everywhere?
  204. segment_index_t s = segment_index_of( h );
  205. h -= segment_base(s);
  206. segment_ptr_t seg = my_table[s];
  207. __TBB_ASSERT( is_valid(seg), "hashcode must be cut by valid mask for allocated segments" );
  208. return &seg[h];
  209. }
  210. // internal serial rehashing helper
  211. void mark_rehashed_levels( hashcode_t h ) throw () {
  212. segment_index_t s = segment_index_of( h );
  213. while( segment_ptr_t seg = my_table[++s] )
  214. if( seg[h].node_list == rehash_req ) {
  215. seg[h].node_list = empty_rehashed;
  216. mark_rehashed_levels( h + ((hashcode_t)1<<s) ); // optimized segment_base(s)
  217. }
  218. }
  219. //! Check for mask race
  220. // Splitting into two functions should help inlining
  221. inline bool check_mask_race( const hashcode_t h, hashcode_t &m ) const {
  222. hashcode_t m_now, m_old = m;
  223. m_now = (hashcode_t) itt_load_word_with_acquire( my_mask );
  224. if( m_old != m_now )
  225. return check_rehashing_collision( h, m_old, m = m_now );
  226. return false;
  227. }
  228. //! Process mask race, check for rehashing collision
  229. bool check_rehashing_collision( const hashcode_t h, hashcode_t m_old, hashcode_t m ) const {
  230. __TBB_ASSERT(m_old != m, NULL); // TODO?: m arg could be optimized out by passing h = h&m
  231. if( (h & m_old) != (h & m) ) { // mask changed for this hashcode, rare event
  232. // condition above proves that 'h' has some other bits set beside 'm_old'
  233. // find next applicable mask after m_old //TODO: look at bsl instruction
  234. for( ++m_old; !(h & m_old); m_old <<= 1 ) // at maximum few rounds depending on the first block size
  235. ;
  236. m_old = (m_old<<1) - 1; // get full mask from a bit
  237. __TBB_ASSERT((m_old&(m_old+1))==0 && m_old <= m, NULL);
  238. // check whether it is rehashing/ed
  239. if( itt_load_word_with_acquire(get_bucket(h & m_old)->node_list) != rehash_req )
  240. {
  241. #if __TBB_STATISTICS
  242. my_info_restarts++; // race collisions
  243. #endif
  244. return true;
  245. }
  246. }
  247. return false;
  248. }
  249. //! Insert a node and check for load factor. @return segment index to enable.
  250. segment_index_t insert_new_node( bucket *b, node_base *n, hashcode_t mask ) {
  251. size_type sz = ++my_size; // prefix form is to enforce allocation after the first item inserted
  252. add_to_bucket( b, n );
  253. // check load factor
  254. if( sz >= mask ) { // TODO: add custom load_factor
  255. segment_index_t new_seg = __TBB_Log2( mask+1 ); //optimized segment_index_of
  256. __TBB_ASSERT( is_valid(my_table[new_seg-1]), "new allocations must not publish new mask until segment has allocated");
  257. if( !itt_hide_load_word(my_table[new_seg])
  258. && __TBB_CompareAndSwapW(&my_table[new_seg], 2, 0) == 0 )
  259. return new_seg; // The value must be processed
  260. }
  261. return 0;
  262. }
  263. //! Prepare enough segments for number of buckets
  264. void reserve(size_type buckets) {
  265. if( !buckets-- ) return;
  266. bool is_initial = !my_size;
  267. for( size_type m = my_mask; buckets > m; m = my_mask )
  268. enable_segment( segment_index_of( m+1 ), is_initial );
  269. }
  270. //! Swap hash_map_bases
  271. void internal_swap(hash_map_base &table) {
  272. std::swap(this->my_mask, table.my_mask);
  273. std::swap(this->my_size, table.my_size);
  274. for(size_type i = 0; i < embedded_buckets; i++)
  275. std::swap(this->my_embedded_segment[i].node_list, table.my_embedded_segment[i].node_list);
  276. for(size_type i = embedded_block; i < pointers_per_table; i++)
  277. std::swap(this->my_table[i], table.my_table[i]);
  278. }
  279. };
  280. template<typename Iterator>
  281. class hash_map_range;
  282. //! Meets requirements of a forward iterator for STL */
  283. /** Value is either the T or const T type of the container.
  284. @ingroup containers */
  285. template<typename Container, typename Value>
  286. class hash_map_iterator
  287. : public std::iterator<std::forward_iterator_tag,Value>
  288. {
  289. typedef Container map_type;
  290. typedef typename Container::node node;
  291. typedef hash_map_base::node_base node_base;
  292. typedef hash_map_base::bucket bucket;
  293. template<typename C, typename T, typename U>
  294. friend bool operator==( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
  295. template<typename C, typename T, typename U>
  296. friend bool operator!=( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
  297. template<typename C, typename T, typename U>
  298. friend ptrdiff_t operator-( const hash_map_iterator<C,T>& i, const hash_map_iterator<C,U>& j );
  299. template<typename C, typename U>
  300. friend class hash_map_iterator;
  301. template<typename I>
  302. friend class hash_map_range;
  303. void advance_to_next_bucket() { // TODO?: refactor to iterator_base class
  304. size_t k = my_index+1;
  305. while( my_bucket && k <= my_map->my_mask ) {
  306. // Following test uses 2's-complement wizardry
  307. if( k& (k-2) ) // not the beginning of a segment
  308. ++my_bucket;
  309. else my_bucket = my_map->get_bucket( k );
  310. my_node = static_cast<node*>( my_bucket->node_list );
  311. if( hash_map_base::is_valid(my_node) ) {
  312. my_index = k; return;
  313. }
  314. ++k;
  315. }
  316. my_bucket = 0; my_node = 0; my_index = k; // the end
  317. }
  318. #if !defined(_MSC_VER) || defined(__INTEL_COMPILER)
  319. template<typename Key, typename T, typename HashCompare, typename A>
  320. friend class interface5::concurrent_hash_map;
  321. #else
  322. public: // workaround
  323. #endif
  324. //! concurrent_hash_map over which we are iterating.
  325. const Container *my_map;
  326. //! Index in hash table for current item
  327. size_t my_index;
  328. //! Pointer to bucket
  329. const bucket *my_bucket;
  330. //! Pointer to node that has current item
  331. node *my_node;
  332. hash_map_iterator( const Container &map, size_t index, const bucket *b, node_base *n );
  333. public:
  334. //! Construct undefined iterator
  335. hash_map_iterator() {}
  336. hash_map_iterator( const hash_map_iterator<Container,typename Container::value_type> &other ) :
  337. my_map(other.my_map),
  338. my_index(other.my_index),
  339. my_bucket(other.my_bucket),
  340. my_node(other.my_node)
  341. {}
  342. Value& operator*() const {
  343. __TBB_ASSERT( hash_map_base::is_valid(my_node), "iterator uninitialized or at end of container?" );
  344. return my_node->item;
  345. }
  346. Value* operator->() const {return &operator*();}
  347. hash_map_iterator& operator++();
  348. //! Post increment
  349. hash_map_iterator operator++(int) {
  350. hash_map_iterator old(*this);
  351. operator++();
  352. return old;
  353. }
  354. };
  355. template<typename Container, typename Value>
  356. hash_map_iterator<Container,Value>::hash_map_iterator( const Container &map, size_t index, const bucket *b, node_base *n ) :
  357. my_map(&map),
  358. my_index(index),
  359. my_bucket(b),
  360. my_node( static_cast<node*>(n) )
  361. {
  362. if( b && !hash_map_base::is_valid(n) )
  363. advance_to_next_bucket();
  364. }
  365. template<typename Container, typename Value>
  366. hash_map_iterator<Container,Value>& hash_map_iterator<Container,Value>::operator++() {
  367. my_node = static_cast<node*>( my_node->next );
  368. if( !my_node ) advance_to_next_bucket();
  369. return *this;
  370. }
  371. template<typename Container, typename T, typename U>
  372. bool operator==( const hash_map_iterator<Container,T>& i, const hash_map_iterator<Container,U>& j ) {
  373. return i.my_node == j.my_node && i.my_map == j.my_map;
  374. }
  375. template<typename Container, typename T, typename U>
  376. bool operator!=( const hash_map_iterator<Container,T>& i, const hash_map_iterator<Container,U>& j ) {
  377. return i.my_node != j.my_node || i.my_map != j.my_map;
  378. }
  379. //! Range class used with concurrent_hash_map
  380. /** @ingroup containers */
  381. template<typename Iterator>
  382. class hash_map_range {
  383. typedef typename Iterator::map_type map_type;
  384. Iterator my_begin;
  385. Iterator my_end;
  386. mutable Iterator my_midpoint;
  387. size_t my_grainsize;
  388. //! Set my_midpoint to point approximately half way between my_begin and my_end.
  389. void set_midpoint() const;
  390. template<typename U> friend class hash_map_range;
  391. public:
  392. //! Type for size of a range
  393. typedef std::size_t size_type;
  394. typedef typename Iterator::value_type value_type;
  395. typedef typename Iterator::reference reference;
  396. typedef typename Iterator::difference_type difference_type;
  397. typedef Iterator iterator;
  398. //! True if range is empty.
  399. bool empty() const {return my_begin==my_end;}
  400. //! True if range can be partitioned into two subranges.
  401. bool is_divisible() const {
  402. return my_midpoint!=my_end;
  403. }
  404. //! Split range.
  405. hash_map_range( hash_map_range& r, split ) :
  406. my_end(r.my_end),
  407. my_grainsize(r.my_grainsize)
  408. {
  409. r.my_end = my_begin = r.my_midpoint;
  410. __TBB_ASSERT( !empty(), "Splitting despite the range is not divisible" );
  411. __TBB_ASSERT( !r.empty(), "Splitting despite the range is not divisible" );
  412. set_midpoint();
  413. r.set_midpoint();
  414. }
  415. //! type conversion
  416. template<typename U>
  417. hash_map_range( hash_map_range<U>& r) :
  418. my_begin(r.my_begin),
  419. my_end(r.my_end),
  420. my_midpoint(r.my_midpoint),
  421. my_grainsize(r.my_grainsize)
  422. {}
  423. #if TBB_DEPRECATED
  424. //! Init range with iterators and grainsize specified
  425. hash_map_range( const Iterator& begin_, const Iterator& end_, size_type grainsize_ = 1 ) :
  426. my_begin(begin_),
  427. my_end(end_),
  428. my_grainsize(grainsize_)
  429. {
  430. if(!my_end.my_index && !my_end.my_bucket) // end
  431. my_end.my_index = my_end.my_map->my_mask + 1;
  432. set_midpoint();
  433. __TBB_ASSERT( grainsize_>0, "grainsize must be positive" );
  434. }
  435. #endif
  436. //! Init range with container and grainsize specified
  437. hash_map_range( const map_type &map, size_type grainsize_ = 1 ) :
  438. my_begin( Iterator( map, 0, map.my_embedded_segment, map.my_embedded_segment->node_list ) ),
  439. my_end( Iterator( map, map.my_mask + 1, 0, 0 ) ),
  440. my_grainsize( grainsize_ )
  441. {
  442. __TBB_ASSERT( grainsize_>0, "grainsize must be positive" );
  443. set_midpoint();
  444. }
  445. const Iterator& begin() const {return my_begin;}
  446. const Iterator& end() const {return my_end;}
  447. //! The grain size for this range.
  448. size_type grainsize() const {return my_grainsize;}
  449. };
  450. template<typename Iterator>
  451. void hash_map_range<Iterator>::set_midpoint() const {
  452. // Split by groups of nodes
  453. size_t m = my_end.my_index-my_begin.my_index;
  454. if( m > my_grainsize ) {
  455. m = my_begin.my_index + m/2u;
  456. hash_map_base::bucket *b = my_begin.my_map->get_bucket(m);
  457. my_midpoint = Iterator(*my_begin.my_map,m,b,b->node_list);
  458. } else {
  459. my_midpoint = my_end;
  460. }
  461. __TBB_ASSERT( my_begin.my_index <= my_midpoint.my_index,
  462. "my_begin is after my_midpoint" );
  463. __TBB_ASSERT( my_midpoint.my_index <= my_end.my_index,
  464. "my_midpoint is after my_end" );
  465. __TBB_ASSERT( my_begin != my_midpoint || my_begin == my_end,
  466. "[my_begin, my_midpoint) range should not be empty" );
  467. }
  468. } // internal
  469. //! @endcond
  470. //! Unordered map from Key to T.
  471. /** concurrent_hash_map is associative container with concurrent access.
  472. @par Compatibility
  473. The class meets all Container Requirements from C++ Standard (See ISO/IEC 14882:2003(E), clause 23.1).
  474. @par Exception Safety
  475. - Hash function is not permitted to throw an exception. User-defined types Key and T are forbidden from throwing an exception in destructors.
  476. - If exception happens during insert() operations, it has no effect (unless exception raised by HashCompare::hash() function during grow_segment).
  477. - If exception happens during operator=() operation, the container can have a part of source items, and methods size() and empty() can return wrong results.
  478. @par Changes since TBB 2.1
  479. - Replaced internal algorithm and data structure. Patent is pending.
  480. - Added buckets number argument for constructor
  481. @par Changes since TBB 2.0
  482. - Fixed exception-safety
  483. - Added template argument for allocator
  484. - Added allocator argument in constructors
  485. - Added constructor from a range of iterators
  486. - Added several new overloaded insert() methods
  487. - Added get_allocator()
  488. - Added swap()
  489. - Added count()
  490. - Added overloaded erase(accessor &) and erase(const_accessor&)
  491. - Added equal_range() [const]
  492. - Added [const_]pointer, [const_]reference, and allocator_type types
  493. - Added global functions: operator==(), operator!=(), and swap()
  494. @ingroup containers */
  495. template<typename Key, typename T, typename HashCompare, typename Allocator>
  496. class concurrent_hash_map : protected internal::hash_map_base {
  497. template<typename Container, typename Value>
  498. friend class internal::hash_map_iterator;
  499. template<typename I>
  500. friend class internal::hash_map_range;
  501. public:
  502. typedef Key key_type;
  503. typedef T mapped_type;
  504. typedef std::pair<const Key,T> value_type;
  505. typedef hash_map_base::size_type size_type;
  506. typedef ptrdiff_t difference_type;
  507. typedef value_type *pointer;
  508. typedef const value_type *const_pointer;
  509. typedef value_type &reference;
  510. typedef const value_type &const_reference;
  511. typedef internal::hash_map_iterator<concurrent_hash_map,value_type> iterator;
  512. typedef internal::hash_map_iterator<concurrent_hash_map,const value_type> const_iterator;
  513. typedef internal::hash_map_range<iterator> range_type;
  514. typedef internal::hash_map_range<const_iterator> const_range_type;
  515. typedef Allocator allocator_type;
  516. protected:
  517. friend class const_accessor;
  518. struct node;
  519. typedef typename Allocator::template rebind<node>::other node_allocator_type;
  520. node_allocator_type my_allocator;
  521. HashCompare my_hash_compare;
  522. struct node : public node_base {
  523. value_type item;
  524. node( const Key &key ) : item(key, T()) {}
  525. node( const Key &key, const T &t ) : item(key, t) {}
  526. // exception-safe allocation, see C++ Standard 2003, clause 5.3.4p17
  527. void *operator new( size_t /*size*/, node_allocator_type &a ) {
  528. void *ptr = a.allocate(1);
  529. if(!ptr)
  530. tbb::internal::throw_exception(tbb::internal::eid_bad_alloc);
  531. return ptr;
  532. }
  533. // match placement-new form above to be called if exception thrown in constructor
  534. void operator delete( void *ptr, node_allocator_type &a ) { a.deallocate(static_cast<node*>(ptr),1); }
  535. };
  536. void delete_node( node_base *n ) {
  537. my_allocator.destroy( static_cast<node*>(n) );
  538. my_allocator.deallocate( static_cast<node*>(n), 1);
  539. }
  540. node *search_bucket( const key_type &key, bucket *b ) const {
  541. node *n = static_cast<node*>( b->node_list );
  542. while( is_valid(n) && !my_hash_compare.equal(key, n->item.first) )
  543. n = static_cast<node*>( n->next );
  544. __TBB_ASSERT(n != internal::rehash_req, "Search can be executed only for rehashed bucket");
  545. return n;
  546. }
  547. //! bucket accessor is to find, rehash, acquire a lock, and access a bucket
  548. class bucket_accessor : public bucket::scoped_t {
  549. bucket *my_b;
  550. public:
  551. bucket_accessor( concurrent_hash_map *base, const hashcode_t h, bool writer = false ) { acquire( base, h, writer ); }
  552. //! find a bucket by masked hashcode, optionally rehash, and acquire the lock
  553. inline void acquire( concurrent_hash_map *base, const hashcode_t h, bool writer = false ) {
  554. my_b = base->get_bucket( h );
  555. // TODO: actually, notification is unnecessary here, just hiding double-check
  556. if( itt_load_word_with_acquire(my_b->node_list) == internal::rehash_req
  557. && try_acquire( my_b->mutex, /*write=*/true ) )
  558. {
  559. if( my_b->node_list == internal::rehash_req ) base->rehash_bucket( my_b, h ); //recursive rehashing
  560. }
  561. else bucket::scoped_t::acquire( my_b->mutex, writer );
  562. __TBB_ASSERT( my_b->node_list != internal::rehash_req, NULL);
  563. }
  564. //! check whether bucket is locked for write
  565. bool is_writer() { return bucket::scoped_t::is_writer; }
  566. //! get bucket pointer
  567. bucket *operator() () { return my_b; }
  568. };
  569. // TODO refactor to hash_base
  570. void rehash_bucket( bucket *b_new, const hashcode_t h ) {
  571. __TBB_ASSERT( *(intptr_t*)(&b_new->mutex), "b_new must be locked (for write)");
  572. __TBB_ASSERT( h > 1, "The lowermost buckets can't be rehashed" );
  573. __TBB_store_with_release(b_new->node_list, internal::empty_rehashed); // mark rehashed
  574. hashcode_t mask = ( 1u<<__TBB_Log2( h ) ) - 1; // get parent mask from the topmost bit
  575. #if __TBB_STATISTICS
  576. my_info_rehashes++; // invocations of rehash_bucket
  577. #endif
  578. bucket_accessor b_old( this, h & mask );
  579. mask = (mask<<1) | 1; // get full mask for new bucket
  580. __TBB_ASSERT( (mask&(mask+1))==0 && (h & mask) == h, NULL );
  581. restart:
  582. for( node_base **p = &b_old()->node_list, *n = __TBB_load_with_acquire(*p); is_valid(n); n = *p ) {
  583. hashcode_t c = my_hash_compare.hash( static_cast<node*>(n)->item.first );
  584. #if TBB_USE_ASSERT
  585. hashcode_t bmask = h & (mask>>1);
  586. bmask = bmask==0? 1 : ( 1u<<(__TBB_Log2( bmask )+1 ) ) - 1; // minimal mask of parent bucket
  587. __TBB_ASSERT( (c & bmask) == (h & bmask), "hash() function changed for key in table" );
  588. #endif
  589. if( (c & mask) == h ) {
  590. if( !b_old.is_writer() )
  591. if( !b_old.upgrade_to_writer() ) {
  592. goto restart; // node ptr can be invalid due to concurrent erase
  593. }
  594. *p = n->next; // exclude from b_old
  595. add_to_bucket( b_new, n );
  596. } else p = &n->next; // iterate to next item
  597. }
  598. }
  599. public:
  600. class accessor;
  601. //! Combines data access, locking, and garbage collection.
  602. class const_accessor : private node::scoped_t /*which derived from no_copy*/ {
  603. friend class concurrent_hash_map<Key,T,HashCompare,Allocator>;
  604. friend class accessor;
  605. public:
  606. //! Type of value
  607. typedef const typename concurrent_hash_map::value_type value_type;
  608. //! True if result is empty.
  609. bool empty() const {return !my_node;}
  610. //! Set to null
  611. void release() {
  612. if( my_node ) {
  613. node::scoped_t::release();
  614. my_node = 0;
  615. }
  616. }
  617. //! Return reference to associated value in hash table.
  618. const_reference operator*() const {
  619. __TBB_ASSERT( my_node, "attempt to dereference empty accessor" );
  620. return my_node->item;
  621. }
  622. //! Return pointer to associated value in hash table.
  623. const_pointer operator->() const {
  624. return &operator*();
  625. }
  626. //! Create empty result
  627. const_accessor() : my_node(NULL) {}
  628. //! Destroy result after releasing the underlying reference.
  629. ~const_accessor() {
  630. my_node = NULL; // scoped lock's release() is called in its destructor
  631. }
  632. protected:
  633. bool is_writer() { return node::scoped_t::is_writer; }
  634. node *my_node;
  635. hashcode_t my_hash;
  636. };
  637. //! Allows write access to elements and combines data access, locking, and garbage collection.
  638. class accessor: public const_accessor {
  639. public:
  640. //! Type of value
  641. typedef typename concurrent_hash_map::value_type value_type;
  642. //! Return reference to associated value in hash table.
  643. reference operator*() const {
  644. __TBB_ASSERT( this->my_node, "attempt to dereference empty accessor" );
  645. return this->my_node->item;
  646. }
  647. //! Return pointer to associated value in hash table.
  648. pointer operator->() const {
  649. return &operator*();
  650. }
  651. };
  652. //! Construct empty table.
  653. concurrent_hash_map(const allocator_type &a = allocator_type())
  654. : internal::hash_map_base(), my_allocator(a)
  655. {}
  656. //! Construct empty table with n preallocated buckets. This number serves also as initial concurrency level.
  657. concurrent_hash_map(size_type n, const allocator_type &a = allocator_type())
  658. : my_allocator(a)
  659. {
  660. reserve( n );
  661. }
  662. //! Copy constructor
  663. concurrent_hash_map( const concurrent_hash_map& table, const allocator_type &a = allocator_type())
  664. : internal::hash_map_base(), my_allocator(a)
  665. {
  666. internal_copy(table);
  667. }
  668. //! Construction with copying iteration range and given allocator instance
  669. template<typename I>
  670. concurrent_hash_map(I first, I last, const allocator_type &a = allocator_type())
  671. : my_allocator(a)
  672. {
  673. reserve( std::distance(first, last) ); // TODO: load_factor?
  674. internal_copy(first, last);
  675. }
  676. //! Assignment
  677. concurrent_hash_map& operator=( const concurrent_hash_map& table ) {
  678. if( this!=&table ) {
  679. clear();
  680. internal_copy(table);
  681. }
  682. return *this;
  683. }
  684. //! Rehashes and optionally resizes the whole table.
  685. /** Useful to optimize performance before or after concurrent operations.
  686. Also enables using of find() and count() concurrent methods in serial context. */
  687. void rehash(size_type n = 0);
  688. //! Clear table
  689. void clear();
  690. //! Clear table and destroy it.
  691. ~concurrent_hash_map() { clear(); }
  692. //------------------------------------------------------------------------
  693. // Parallel algorithm support
  694. //------------------------------------------------------------------------
  695. range_type range( size_type grainsize=1 ) {
  696. return range_type( *this, grainsize );
  697. }
  698. const_range_type range( size_type grainsize=1 ) const {
  699. return const_range_type( *this, grainsize );
  700. }
  701. //------------------------------------------------------------------------
  702. // STL support - not thread-safe methods
  703. //------------------------------------------------------------------------
  704. iterator begin() {return iterator(*this,0,my_embedded_segment,my_embedded_segment->node_list);}
  705. iterator end() {return iterator(*this,0,0,0);}
  706. const_iterator begin() const {return const_iterator(*this,0,my_embedded_segment,my_embedded_segment->node_list);}
  707. const_iterator end() const {return const_iterator(*this,0,0,0);}
  708. std::pair<iterator, iterator> equal_range( const Key& key ) { return internal_equal_range(key, end()); }
  709. std::pair<const_iterator, const_iterator> equal_range( const Key& key ) const { return internal_equal_range(key, end()); }
  710. //! Number of items in table.
  711. size_type size() const { return my_size; }
  712. //! True if size()==0.
  713. bool empty() const { return my_size == 0; }
  714. //! Upper bound on size.
  715. size_type max_size() const {return (~size_type(0))/sizeof(node);}
  716. //! Returns the current number of buckets
  717. size_type bucket_count() const { return my_mask+1; }
  718. //! return allocator object
  719. allocator_type get_allocator() const { return this->my_allocator; }
  720. //! swap two instances. Iterators are invalidated
  721. void swap(concurrent_hash_map &table);
  722. //------------------------------------------------------------------------
  723. // concurrent map operations
  724. //------------------------------------------------------------------------
  725. //! Return count of items (0 or 1)
  726. size_type count( const Key &key ) const {
  727. return const_cast<concurrent_hash_map*>(this)->lookup(/*insert*/false, key, NULL, NULL, /*write=*/false );
  728. }
  729. //! Find item and acquire a read lock on the item.
  730. /** Return true if item is found, false otherwise. */
  731. bool find( const_accessor &result, const Key &key ) const {
  732. result.release();
  733. return const_cast<concurrent_hash_map*>(this)->lookup(/*insert*/false, key, NULL, &result, /*write=*/false );
  734. }
  735. //! Find item and acquire a write lock on the item.
  736. /** Return true if item is found, false otherwise. */
  737. bool find( accessor &result, const Key &key ) {
  738. result.release();
  739. return lookup(/*insert*/false, key, NULL, &result, /*write=*/true );
  740. }
  741. //! Insert item (if not already present) and acquire a read lock on the item.
  742. /** Returns true if item is new. */
  743. bool insert( const_accessor &result, const Key &key ) {
  744. result.release();
  745. return lookup(/*insert*/true, key, NULL, &result, /*write=*/false );
  746. }
  747. //! Insert item (if not already present) and acquire a write lock on the item.
  748. /** Returns true if item is new. */
  749. bool insert( accessor &result, const Key &key ) {
  750. result.release();
  751. return lookup(/*insert*/true, key, NULL, &result, /*write=*/true );
  752. }
  753. //! Insert item by copying if there is no such key present already and acquire a read lock on the item.
  754. /** Returns true if item is new. */
  755. bool insert( const_accessor &result, const value_type &value ) {
  756. result.release();
  757. return lookup(/*insert*/true, value.first, &value.second, &result, /*write=*/false );
  758. }
  759. //! Insert item by copying if there is no such key present already and acquire a write lock on the item.
  760. /** Returns true if item is new. */
  761. bool insert( accessor &result, const value_type &value ) {
  762. result.release();
  763. return lookup(/*insert*/true, value.first, &value.second, &result, /*write=*/true );
  764. }
  765. //! Insert item by copying if there is no such key present already
  766. /** Returns true if item is inserted. */
  767. bool insert( const value_type &value ) {
  768. return lookup(/*insert*/true, value.first, &value.second, NULL, /*write=*/false );
  769. }
  770. //! Insert range [first, last)
  771. template<typename I>
  772. void insert(I first, I last) {
  773. for(; first != last; ++first)
  774. insert( *first );
  775. }
  776. //! Erase item.
  777. /** Return true if item was erased by particularly this call. */
  778. bool erase( const Key& key );
  779. //! Erase item by const_accessor.
  780. /** Return true if item was erased by particularly this call. */
  781. bool erase( const_accessor& item_accessor ) {
  782. return exclude( item_accessor );
  783. }
  784. //! Erase item by accessor.
  785. /** Return true if item was erased by particularly this call. */
  786. bool erase( accessor& item_accessor ) {
  787. return exclude( item_accessor );
  788. }
  789. protected:
  790. //! Insert or find item and optionally acquire a lock on the item.
  791. bool lookup( bool op_insert, const Key &key, const T *t, const_accessor *result, bool write );
  792. //! delete item by accessor
  793. bool exclude( const_accessor &item_accessor );
  794. //! Returns an iterator for an item defined by the key, or for the next item after it (if upper==true)
  795. template<typename I>
  796. std::pair<I, I> internal_equal_range( const Key& key, I end ) const;
  797. //! Copy "source" to *this, where *this must start out empty.
  798. void internal_copy( const concurrent_hash_map& source );
  799. template<typename I>
  800. void internal_copy(I first, I last);
  801. //! Fast find when no concurrent erasure is used. For internal use inside TBB only!
  802. /** Return pointer to item with given key, or NULL if no such item exists.
  803. Must not be called concurrently with erasure operations. */
  804. const_pointer internal_fast_find( const Key& key ) const {
  805. hashcode_t h = my_hash_compare.hash( key );
  806. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  807. node *n;
  808. restart:
  809. __TBB_ASSERT((m&(m+1))==0, NULL);
  810. bucket *b = get_bucket( h & m );
  811. // TODO: actually, notification is unnecessary here, just hiding double-check
  812. if( itt_load_word_with_acquire(b->node_list) == internal::rehash_req )
  813. {
  814. bucket::scoped_t lock;
  815. if( lock.try_acquire( b->mutex, /*write=*/true ) ) {
  816. if( b->node_list == internal::rehash_req)
  817. const_cast<concurrent_hash_map*>(this)->rehash_bucket( b, h & m ); //recursive rehashing
  818. }
  819. else lock.acquire( b->mutex, /*write=*/false );
  820. __TBB_ASSERT(b->node_list!=internal::rehash_req,NULL);
  821. }
  822. n = search_bucket( key, b );
  823. if( n )
  824. return &n->item;
  825. else if( check_mask_race( h, m ) )
  826. goto restart;
  827. return 0;
  828. }
  829. };
  830. #if _MSC_VER && !defined(__INTEL_COMPILER)
  831. // Suppress "conditional expression is constant" warning.
  832. #pragma warning( push )
  833. #pragma warning( disable: 4127 )
  834. #endif
  835. template<typename Key, typename T, typename HashCompare, typename A>
  836. bool concurrent_hash_map<Key,T,HashCompare,A>::lookup( bool op_insert, const Key &key, const T *t, const_accessor *result, bool write ) {
  837. __TBB_ASSERT( !result || !result->my_node, NULL );
  838. bool return_value;
  839. hashcode_t const h = my_hash_compare.hash( key );
  840. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  841. segment_index_t grow_segment = 0;
  842. node *n, *tmp_n = 0;
  843. restart:
  844. {//lock scope
  845. __TBB_ASSERT((m&(m+1))==0, NULL);
  846. return_value = false;
  847. // get bucket
  848. bucket_accessor b( this, h & m );
  849. // find a node
  850. n = search_bucket( key, b() );
  851. if( op_insert ) {
  852. // [opt] insert a key
  853. if( !n ) {
  854. if( !tmp_n ) {
  855. if(t) tmp_n = new( my_allocator ) node(key, *t);
  856. else tmp_n = new( my_allocator ) node(key);
  857. }
  858. if( !b.is_writer() && !b.upgrade_to_writer() ) { // TODO: improved insertion
  859. // Rerun search_list, in case another thread inserted the item during the upgrade.
  860. n = search_bucket( key, b() );
  861. if( is_valid(n) ) { // unfortunately, it did
  862. b.downgrade_to_reader();
  863. goto exists;
  864. }
  865. }
  866. if( check_mask_race(h, m) )
  867. goto restart; // b.release() is done in ~b().
  868. // insert and set flag to grow the container
  869. grow_segment = insert_new_node( b(), n = tmp_n, m );
  870. tmp_n = 0;
  871. return_value = true;
  872. }
  873. } else { // find or count
  874. if( !n ) {
  875. if( check_mask_race( h, m ) )
  876. goto restart; // b.release() is done in ~b(). TODO: replace by continue
  877. return false;
  878. }
  879. return_value = true;
  880. }
  881. exists:
  882. if( !result ) goto check_growth;
  883. // TODO: the following seems as generic/regular operation
  884. // acquire the item
  885. if( !result->try_acquire( n->mutex, write ) ) {
  886. // we are unlucky, prepare for longer wait
  887. tbb::internal::atomic_backoff trials;
  888. do {
  889. if( !trials.bounded_pause() ) {
  890. // the wait takes really long, restart the operation
  891. b.release();
  892. __TBB_ASSERT( !op_insert || !return_value, "Can't acquire new item in locked bucket?" );
  893. __TBB_Yield();
  894. m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  895. goto restart;
  896. }
  897. } while( !result->try_acquire( n->mutex, write ) );
  898. }
  899. }//lock scope
  900. result->my_node = n;
  901. result->my_hash = h;
  902. check_growth:
  903. // [opt] grow the container
  904. if( grow_segment ) {
  905. #if __TBB_STATISTICS
  906. my_info_resizes++; // concurrent ones
  907. #endif
  908. enable_segment( grow_segment );
  909. }
  910. if( tmp_n ) // if op_insert only
  911. delete_node( tmp_n );
  912. return return_value;
  913. }
  914. template<typename Key, typename T, typename HashCompare, typename A>
  915. template<typename I>
  916. std::pair<I, I> concurrent_hash_map<Key,T,HashCompare,A>::internal_equal_range( const Key& key, I end_ ) const {
  917. hashcode_t h = my_hash_compare.hash( key );
  918. hashcode_t m = my_mask;
  919. __TBB_ASSERT((m&(m+1))==0, NULL);
  920. h &= m;
  921. bucket *b = get_bucket( h );
  922. while( b->node_list == internal::rehash_req ) {
  923. m = ( 1u<<__TBB_Log2( h ) ) - 1; // get parent mask from the topmost bit
  924. b = get_bucket( h &= m );
  925. }
  926. node *n = search_bucket( key, b );
  927. if( !n )
  928. return std::make_pair(end_, end_);
  929. iterator lower(*this, h, b, n), upper(lower);
  930. return std::make_pair(lower, ++upper);
  931. }
  932. template<typename Key, typename T, typename HashCompare, typename A>
  933. bool concurrent_hash_map<Key,T,HashCompare,A>::exclude( const_accessor &item_accessor ) {
  934. __TBB_ASSERT( item_accessor.my_node, NULL );
  935. node_base *const n = item_accessor.my_node;
  936. hashcode_t const h = item_accessor.my_hash;
  937. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  938. do {
  939. // get bucket
  940. bucket_accessor b( this, h & m, /*writer=*/true );
  941. node_base **p = &b()->node_list;
  942. while( *p && *p != n )
  943. p = &(*p)->next;
  944. if( !*p ) { // someone else was first
  945. if( check_mask_race( h, m ) )
  946. continue;
  947. item_accessor.release();
  948. return false;
  949. }
  950. __TBB_ASSERT( *p == n, NULL );
  951. *p = n->next; // remove from container
  952. my_size--;
  953. break;
  954. } while(true);
  955. if( !item_accessor.is_writer() ) // need to get exclusive lock
  956. item_accessor.upgrade_to_writer(); // return value means nothing here
  957. item_accessor.release();
  958. delete_node( n ); // Only one thread can delete it
  959. return true;
  960. }
  961. template<typename Key, typename T, typename HashCompare, typename A>
  962. bool concurrent_hash_map<Key,T,HashCompare,A>::erase( const Key &key ) {
  963. node_base *n;
  964. hashcode_t const h = my_hash_compare.hash( key );
  965. hashcode_t m = (hashcode_t) itt_load_word_with_acquire( my_mask );
  966. restart:
  967. {//lock scope
  968. // get bucket
  969. bucket_accessor b( this, h & m );
  970. search:
  971. node_base **p = &b()->node_list;
  972. n = *p;
  973. while( is_valid(n) && !my_hash_compare.equal(key, static_cast<node*>(n)->item.first ) ) {
  974. p = &n->next;
  975. n = *p;
  976. }
  977. if( !n ) { // not found, but mask could be changed
  978. if( check_mask_race( h, m ) )
  979. goto restart;
  980. return false;
  981. }
  982. else if( !b.is_writer() && !b.upgrade_to_writer() ) {
  983. if( check_mask_race( h, m ) ) // contended upgrade, check mask
  984. goto restart;
  985. goto search;
  986. }
  987. *p = n->next;
  988. my_size--;
  989. }
  990. {
  991. typename node::scoped_t item_locker( n->mutex, /*write=*/true );
  992. }
  993. // note: there should be no threads pretending to acquire this mutex again, do not try to upgrade const_accessor!
  994. delete_node( n ); // Only one thread can delete it due to write lock on the bucket
  995. return true;
  996. }
  997. template<typename Key, typename T, typename HashCompare, typename A>
  998. void concurrent_hash_map<Key,T,HashCompare,A>::swap(concurrent_hash_map<Key,T,HashCompare,A> &table) {
  999. std::swap(this->my_allocator, table.my_allocator);
  1000. std::swap(this->my_hash_compare, table.my_hash_compare);
  1001. internal_swap(table);
  1002. }
  1003. template<typename Key, typename T, typename HashCompare, typename A>
  1004. void concurrent_hash_map<Key,T,HashCompare,A>::rehash(size_type sz) {
  1005. reserve( sz ); // TODO: add reduction of number of buckets as well
  1006. hashcode_t mask = my_mask;
  1007. hashcode_t b = (mask+1)>>1; // size or first index of the last segment
  1008. __TBB_ASSERT((b&(b-1))==0, NULL); // zero or power of 2
  1009. bucket *bp = get_bucket( b ); // only the last segment should be scanned for rehashing
  1010. for(; b <= mask; b++, bp++ ) {
  1011. node_base *n = bp->node_list;
  1012. __TBB_ASSERT( is_valid(n) || n == internal::empty_rehashed || n == internal::rehash_req, "Broken internal structure" );
  1013. __TBB_ASSERT( *reinterpret_cast<intptr_t*>(&bp->mutex) == 0, "concurrent or unexpectedly terminated operation during rehash() execution" );
  1014. if( n == internal::rehash_req ) { // rehash bucket, conditional because rehashing of a previous bucket may affect this one
  1015. hashcode_t h = b; bucket *b_old = bp;
  1016. do {
  1017. __TBB_ASSERT( h > 1, "The lowermost buckets can't be rehashed" );
  1018. hashcode_t m = ( 1u<<__TBB_Log2( h ) ) - 1; // get parent mask from the topmost bit
  1019. b_old = get_bucket( h &= m );
  1020. } while( b_old->node_list == internal::rehash_req );
  1021. // now h - is index of the root rehashed bucket b_old
  1022. mark_rehashed_levels( h ); // mark all non-rehashed children recursively across all segments
  1023. for( node_base **p = &b_old->node_list, *q = *p; is_valid(q); q = *p ) {
  1024. hashcode_t c = my_hash_compare.hash( static_cast<node*>(q)->item.first );
  1025. if( (c & mask) != h ) { // should be rehashed
  1026. *p = q->next; // exclude from b_old
  1027. bucket *b_new = get_bucket( c & mask );
  1028. __TBB_ASSERT( b_new->node_list != internal::rehash_req, "hash() function changed for key in table or internal error" );
  1029. add_to_bucket( b_new, q );
  1030. } else p = &q->next; // iterate to next item
  1031. }
  1032. }
  1033. }
  1034. #if TBB_USE_PERFORMANCE_WARNINGS
  1035. int current_size = int(my_size), buckets = int(mask)+1, empty_buckets = 0, overpopulated_buckets = 0; // usage statistics
  1036. static bool reported = false;
  1037. #endif
  1038. #if TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS
  1039. for( b = 0; b <= mask; b++ ) {// only last segment should be scanned for rehashing
  1040. if( b & (b-2) ) ++bp; // not the beginning of a segment
  1041. else bp = get_bucket( b );
  1042. node_base *n = bp->node_list;
  1043. __TBB_ASSERT( *reinterpret_cast<intptr_t*>(&bp->mutex) == 0, "concurrent or unexpectedly terminated operation during rehash() execution" );
  1044. __TBB_ASSERT( is_valid(n) || n == internal::empty_rehashed, "Broken internal structure" );
  1045. #if TBB_USE_PERFORMANCE_WARNINGS
  1046. if( n == internal::empty_rehashed ) empty_buckets++;
  1047. else if( n->next ) overpopulated_buckets++;
  1048. #endif
  1049. #if TBB_USE_ASSERT
  1050. for( ; is_valid(n); n = n->next ) {
  1051. hashcode_t h = my_hash_compare.hash( static_cast<node*>(n)->item.first ) & mask;
  1052. __TBB_ASSERT( h == b, "hash() function changed for key in table or internal error" );
  1053. }
  1054. #endif
  1055. }
  1056. #endif // TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS
  1057. #if TBB_USE_PERFORMANCE_WARNINGS
  1058. if( buckets > current_size) empty_buckets -= buckets - current_size;
  1059. else overpopulated_buckets -= current_size - buckets; // TODO: load_factor?
  1060. if( !reported && buckets >= 512 && ( 2*empty_buckets > current_size || 2*overpopulated_buckets > current_size ) ) {
  1061. tbb::internal::runtime_warning(
  1062. "Performance is not optimal because the hash function produces bad randomness in lower bits in %s.\nSize: %d Empties: %d Overlaps: %d",
  1063. typeid(*this).name(), current_size, empty_buckets, overpopulated_buckets );
  1064. reported = true;
  1065. }
  1066. #endif
  1067. }
  1068. template<typename Key, typename T, typename HashCompare, typename A>
  1069. void concurrent_hash_map<Key,T,HashCompare,A>::clear() {
  1070. hashcode_t m = my_mask;
  1071. __TBB_ASSERT((m&(m+1))==0, NULL);
  1072. #if TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1073. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1074. int current_size = int(my_size), buckets = int(m)+1, empty_buckets = 0, overpopulated_buckets = 0; // usage statistics
  1075. static bool reported = false;
  1076. #endif
  1077. bucket *bp = 0;
  1078. // check consistency
  1079. for( segment_index_t b = 0; b <= m; b++ ) {
  1080. if( b & (b-2) ) ++bp; // not the beginning of a segment
  1081. else bp = get_bucket( b );
  1082. node_base *n = bp->node_list;
  1083. __TBB_ASSERT( is_valid(n) || n == internal::empty_rehashed || n == internal::rehash_req, "Broken internal structure" );
  1084. __TBB_ASSERT( *reinterpret_cast<intptr_t*>(&bp->mutex) == 0, "concurrent or unexpectedly terminated operation during clear() execution" );
  1085. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1086. if( n == internal::empty_rehashed ) empty_buckets++;
  1087. else if( n == internal::rehash_req ) buckets--;
  1088. else if( n->next ) overpopulated_buckets++;
  1089. #endif
  1090. #if __TBB_EXTRA_DEBUG
  1091. for(; is_valid(n); n = n->next ) {
  1092. hashcode_t h = my_hash_compare.hash( static_cast<node*>(n)->item.first );
  1093. h &= m;
  1094. __TBB_ASSERT( h == b || get_bucket(h)->node_list == internal::rehash_req, "hash() function changed for key in table or internal error" );
  1095. }
  1096. #endif
  1097. }
  1098. #if TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1099. #if __TBB_STATISTICS
  1100. printf( "items=%d buckets: capacity=%d rehashed=%d empty=%d overpopulated=%d"
  1101. " concurrent: resizes=%u rehashes=%u restarts=%u\n",
  1102. current_size, int(m+1), buckets, empty_buckets, overpopulated_buckets,
  1103. unsigned(my_info_resizes), unsigned(my_info_rehashes), unsigned(my_info_restarts) );
  1104. my_info_resizes = 0; // concurrent ones
  1105. my_info_restarts = 0; // race collisions
  1106. my_info_rehashes = 0; // invocations of rehash_bucket
  1107. #endif
  1108. if( buckets > current_size) empty_buckets -= buckets - current_size;
  1109. else overpopulated_buckets -= current_size - buckets; // TODO: load_factor?
  1110. if( !reported && buckets >= 512 && ( 2*empty_buckets > current_size || 2*overpopulated_buckets > current_size ) ) {
  1111. tbb::internal::runtime_warning(
  1112. "Performance is not optimal because the hash function produces bad randomness in lower bits in %s.\nSize: %d Empties: %d Overlaps: %d",
  1113. typeid(*this).name(), current_size, empty_buckets, overpopulated_buckets );
  1114. reported = true;
  1115. }
  1116. #endif
  1117. #endif//TBB_USE_ASSERT || TBB_USE_PERFORMANCE_WARNINGS || __TBB_STATISTICS
  1118. my_size = 0;
  1119. segment_index_t s = segment_index_of( m );
  1120. __TBB_ASSERT( s+1 == pointers_per_table || !my_table[s+1], "wrong mask or concurrent grow" );
  1121. cache_aligned_allocator<bucket> alloc;
  1122. do {
  1123. __TBB_ASSERT( is_valid( my_table[s] ), "wrong mask or concurrent grow" );
  1124. segment_ptr_t buckets_ptr = my_table[s];
  1125. size_type sz = segment_size( s ? s : 1 );
  1126. for( segment_index_t i = 0; i < sz; i++ )
  1127. for( node_base *n = buckets_ptr[i].node_list; is_valid(n); n = buckets_ptr[i].node_list ) {
  1128. buckets_ptr[i].node_list = n->next;
  1129. delete_node( n );
  1130. }
  1131. if( s >= first_block) // the first segment or the next
  1132. alloc.deallocate( buckets_ptr, sz );
  1133. else if( s == embedded_block && embedded_block != first_block )
  1134. alloc.deallocate( buckets_ptr, segment_size(first_block)-embedded_buckets );
  1135. if( s >= embedded_block ) my_table[s] = 0;
  1136. } while(s-- > 0);
  1137. my_mask = embedded_buckets - 1;
  1138. }
  1139. template<typename Key, typename T, typename HashCompare, typename A>
  1140. void concurrent_hash_map<Key,T,HashCompare,A>::internal_copy( const concurrent_hash_map& source ) {
  1141. reserve( source.my_size ); // TODO: load_factor?
  1142. hashcode_t mask = source.my_mask;
  1143. if( my_mask == mask ) { // optimized version
  1144. bucket *dst = 0, *src = 0;
  1145. bool rehash_required = false;
  1146. for( hashcode_t k = 0; k <= mask; k++ ) {
  1147. if( k & (k-2) ) ++dst,src++; // not the beginning of a segment
  1148. else { dst = get_bucket( k ); src = source.get_bucket( k ); }
  1149. __TBB_ASSERT( dst->node_list != internal::rehash_req, "Invalid bucket in destination table");
  1150. node *n = static_cast<node*>( src->node_list );
  1151. if( n == internal::rehash_req ) { // source is not rehashed, items are in previous buckets
  1152. rehash_required = true;
  1153. dst->node_list = internal::rehash_req;
  1154. } else for(; n; n = static_cast<node*>( n->next ) ) {
  1155. add_to_bucket( dst, new( my_allocator ) node(n->item.first, n->item.second) );
  1156. ++my_size; // TODO: replace by non-atomic op
  1157. }
  1158. }
  1159. if( rehash_required ) rehash();
  1160. } else internal_copy( source.begin(), source.end() );
  1161. }
  1162. template<typename Key, typename T, typename HashCompare, typename A>
  1163. template<typename I>
  1164. void concurrent_hash_map<Key,T,HashCompare,A>::internal_copy(I first, I last) {
  1165. hashcode_t m = my_mask;
  1166. for(; first != last; ++first) {
  1167. hashcode_t h = my_hash_compare.hash( first->first );
  1168. bucket *b = get_bucket( h & m );
  1169. __TBB_ASSERT( b->node_list != internal::rehash_req, "Invalid bucket in destination table");
  1170. node *n = new( my_allocator ) node(first->first, first->second);
  1171. add_to_bucket( b, n );
  1172. ++my_size; // TODO: replace by non-atomic op
  1173. }
  1174. }
  1175. } // namespace interface5
  1176. using interface5::concurrent_hash_map;
  1177. template<typename Key, typename T, typename HashCompare, typename A1, typename A2>
  1178. inline bool operator==(const concurrent_hash_map<Key, T, HashCompare, A1> &a, const concurrent_hash_map<Key, T, HashCompare, A2> &b) {
  1179. if(a.size() != b.size()) return false;
  1180. typename concurrent_hash_map<Key, T, HashCompare, A1>::const_iterator i(a.begin()), i_end(a.end());
  1181. typename concurrent_hash_map<Key, T, HashCompare, A2>::const_iterator j, j_end(b.end());
  1182. for(; i != i_end; ++i) {
  1183. j = b.equal_range(i->first).first;
  1184. if( j == j_end || !(i->second == j->second) ) return false;
  1185. }
  1186. return true;
  1187. }
  1188. template<typename Key, typename T, typename HashCompare, typename A1, typename A2>
  1189. inline bool operator!=(const concurrent_hash_map<Key, T, HashCompare, A1> &a, const concurrent_hash_map<Key, T, HashCompare, A2> &b)
  1190. { return !(a == b); }
  1191. template<typename Key, typename T, typename HashCompare, typename A>
  1192. inline void swap(concurrent_hash_map<Key, T, HashCompare, A> &a, concurrent_hash_map<Key, T, HashCompare, A> &b)
  1193. { a.swap( b ); }
  1194. #if _MSC_VER && !defined(__INTEL_COMPILER)
  1195. #pragma warning( pop )
  1196. #endif // warning 4127 is back
  1197. } // namespace tbb
  1198. #endif /* __TBB_concurrent_hash_map_H */