3 #ifndef __CDS_CONTAINER_MICHAEL_SET_H
4 #define __CDS_CONTAINER_MICHAEL_SET_H
6 #include <cds/container/details/michael_set_base.h>
7 #include <cds/details/allocator.h>
9 namespace cds { namespace container {
11 /// Michael's hash set
12 /** @ingroup cds_nonintrusive_set
13 \anchor cds_nonintrusive_MichaelHashSet_hp
16 - [2002] Maged Michael "High performance dynamic lock-free hash tables and list-based sets"
18 Michael's hash table algorithm is based on lock-free ordered list and it is very simple.
19 The main structure is an array \p T of size \p M. Each element in \p T is basically a pointer
20 to a hash bucket, implemented as a singly linked list. The array of buckets cannot be dynamically expanded.
21 However, each bucket may contain unbounded number of items.
23 Template parameters are:
24 - \p GC - Garbage collector used. You may use any \ref cds_garbage_collector "Garbage collector"
25 from the \p libcds library.
26 Note the \p GC must be the same as the \p GC used for \p OrderedList
27 - \p OrderedList - ordered list implementation used as bucket for hash set, for example, \p MichaelList.
28 The ordered list implementation specifies the type \p T to be stored in the hash-set,
29 the comparing functor for the type \p T and other features specific for the ordered list.
30 - \p Traits - set traits, default is \p michael_set::traits.
31 Instead of defining \p Traits struct you may use option-based syntax with \p michael_set::make_traits metafunction.
33 There are the specializations:
34 - for \ref cds_urcu_desc "RCU" - declared in <tt>cd/container/michael_set_rcu.h</tt>,
35 see \ref cds_nonintrusive_MichaelHashSet_rcu "MichaelHashSet<RCU>".
36 - for \ref cds::gc::nogc declared in <tt>cds/container/michael_set_nogc.h</tt>,
37 see \ref cds_nonintrusive_MichaelHashSet_nogc "MichaelHashSet<gc::nogc>".
39 \anchor cds_nonintrusive_MichaelHashSet_hash_functor
42 Some member functions of Michael's hash set accept the key parameter of type \p Q which differs from node type \p value_type.
43 It is expected that type \p Q contains full key of node type \p value_type, and if keys of type \p Q and \p value_type
44 are equal the hash values of these keys must be equal too.
46 The hash functor \p Traits::hash should accept parameters of both type:
50 std::string key_ ; // key field
56 size_t operator()( const std::string& s ) const
58 return std::hash( s );
61 size_t operator()( const Foo& f ) const
63 return (*this)( f.key_ );
70 The class supports a forward iterator (\ref iterator and \ref const_iterator).
71 The iteration is unordered.
72 The iterator object is thread-safe: the element pointed by the iterator object is guarded,
73 so, the element cannot be reclaimed while the iterator object is alive.
74 However, passing an iterator object between threads is dangerous.
76 @warning Due to concurrent nature of Michael's set it is not guarantee that you can iterate
77 all elements in the set: any concurrent deletion can exclude the element
78 pointed by the iterator from the set, and your iteration can be terminated
79 before end of the set. Therefore, such iteration is more suitable for debugging purpose only
81 Remember, each iterator object requires an additional hazard pointer, that may be
82 a limited resource for \p GC like \p gc::HP (for \p gc::DHP the total count of
85 The iterator class supports the following minimalistic interface:
92 iterator( iterator const& s);
94 value_type * operator ->() const;
95 value_type& operator *() const;
98 iterator& operator ++();
101 iterator& operator = (const iterator& src);
103 bool operator ==(iterator const& i ) const;
104 bool operator !=(iterator const& i ) const;
107 Note, the iterator object returned by \ref end, \p cend member functions points to \p nullptr and should not be dereferenced.
111 Suppose, we have the following type \p Foo that we want to store in our \p %MichaelHashSet:
114 int nKey ; // key field
115 int nVal ; // value field
119 To use \p %MichaelHashSet for \p Foo values, you should first choose suitable ordered list class
120 that will be used as a bucket for the set. We will use \p gc::DHP reclamation schema and
121 \p MichaelList as a bucket type. Also, for ordered list we should develop a comparator for our \p Foo
124 #include <cds/container/michael_list_dhp.h>
125 #include <cds/container/michael_set.h>
127 namespace cc = cds::container;
131 int operator ()(Foo const& v1, Foo const& v2 ) const
133 if ( std::less( v1.nKey, v2.nKey ))
135 return std::less(v2.nKey, v1.nKey) ? 1 : 0;
140 typedef cc::MichaelList< cds::gc::DHP, Foo,
141 typename cc::michael_list::make_traits<
142 cc::opt::compare< Foo_cmp > // item comparator option
146 // Hash functor for Foo
148 size_t operator ()( int i ) const
150 return std::hash( i );
152 size_t operator()( Foo const& i ) const
154 return std::hash( i.nKey );
159 // Note that \p GC template parameter of ordered list must be equal \p GC for the set.
160 typedef cc::MichaelHashSet< cds::gc::DHP, bucket_list,
161 cc::michael_set::make_traits<
162 cc::opt::hash< foo_hash >
173 #ifdef CDS_DOXYGEN_INVOKED
174 class Traits = michael_set::traits
182 typedef GC gc; ///< Garbage collector
183 typedef OrderedList bucket_type; ///< type of ordered list used as a bucket implementation
184 typedef Traits traits; ///< Set traits
186 typedef typename bucket_type::value_type value_type; ///< type of value to be stored in the list
187 typedef typename bucket_type::key_comparator key_comparator; ///< key comparison functor
189 /// Hash functor for \ref value_type and all its derivatives that you use
190 typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
191 typedef typename traits::item_counter item_counter; ///< Item counter type
193 /// Bucket table allocator
194 typedef cds::details::Allocator< bucket_type, typename traits::allocator > bucket_table_allocator;
196 typedef typename bucket_type::guarded_ptr guarded_ptr; ///< Guarded pointer
199 item_counter m_ItemCounter; ///< Item counter
200 hash m_HashFunctor; ///< Hash functor
201 bucket_type * m_Buckets; ///< bucket table
205 const size_t m_nHashBitmask;
210 /// Calculates hash value of \p key
211 template <typename Q>
212 size_t hash_value( Q const& key ) const
214 return m_HashFunctor( key ) & m_nHashBitmask;
217 /// Returns the bucket (ordered list) for \p key
218 template <typename Q>
219 bucket_type& bucket( Q const& key )
221 return m_Buckets[ hash_value( key ) ];
227 typedef michael_set::details::iterator< bucket_type, false > iterator;
229 /// Const forward iterator
230 typedef michael_set::details::iterator< bucket_type, true > const_iterator;
232 /// Returns a forward iterator addressing the first element in a set
234 For empty set \code begin() == end() \endcode
238 return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
241 /// Returns an iterator that addresses the location succeeding the last element in a set
243 Do not use the value returned by <tt>end</tt> function to access any item.
244 The returned value can be used only to control reaching the end of the set.
245 For empty set \code begin() == end() \endcode
249 return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
252 /// Returns a forward const iterator addressing the first element in a set
254 const_iterator begin() const
256 return get_const_begin();
258 const_iterator cbegin() const
260 return get_const_begin();
264 /// Returns an const iterator that addresses the location succeeding the last element in a set
266 const_iterator end() const
268 return get_const_end();
270 const_iterator cend() const
272 return get_const_end();
278 const_iterator get_const_begin() const
280 return const_iterator( const_cast<bucket_type const&>(m_Buckets[0]).begin(), m_Buckets, m_Buckets + bucket_count() );
282 const_iterator get_const_end() const
284 return const_iterator( const_cast<bucket_type const&>(m_Buckets[bucket_count() - 1]).end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
289 /// Initialize hash set
290 /** @anchor cds_nonintrusive_MichaelHashSet_hp_ctor
291 The Michael's hash set is non-expandable container. You should point the average count of items \p nMaxItemCount
292 when you create an object.
293 \p nLoadFactor parameter defines average count of items per bucket and it should be small number between 1 and 10.
294 Remember, since the bucket implementation is an ordered list, searching in the bucket is linear [<tt>O(nLoadFactor)</tt>].
296 The ctor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
299 size_t nMaxItemCount, ///< estimation of max item count in the hash set
300 size_t nLoadFactor ///< load factor: estimation of max number of items in the bucket
301 ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
303 // GC and OrderedList::gc must be the same
304 static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
306 // atomicity::empty_item_counter is not allowed as a item counter
307 static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
308 "cds::atomicity::empty_item_counter is not allowed as a item counter");
310 m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
313 /// Clears hash set and destroys it
317 bucket_table_allocator().Delete( m_Buckets, bucket_count() );
322 The function creates a node with copy of \p val value
323 and then inserts the node created into the set.
325 The type \p Q should contain as minimum the complete key for the node.
326 The object of \ref value_type should be constructible from a value of type \p Q.
327 In trivial case, \p Q is equal to \ref value_type.
329 Returns \p true if \p val is inserted into the set, \p false otherwise.
331 template <typename Q>
332 bool insert( Q const& val )
334 const bool bRet = bucket( val ).insert( val );
342 The function allows to split creating of new item into two part:
343 - create item with key only
344 - insert new item into the set
345 - if inserting is success, calls \p f functor to initialize value-fields of \p val.
347 The functor signature is:
349 void func( value_type& val );
351 where \p val is the item inserted.
352 The user-defined functor is called only if the inserting is success.
354 @warning For \ref cds_nonintrusive_MichaelList_gc "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
355 \ref cds_nonintrusive_LazyList_gc "LazyList" provides exclusive access to inserted item and does not require any node-level
358 template <typename Q, typename Func>
359 bool insert( Q const& val, Func f )
361 const bool bRet = bucket( val ).insert( val, f );
367 /// Ensures that the item exists in the set
369 The operation performs inserting or changing data with lock-free manner.
371 If the \p val key not found in the set, then the new item created from \p val
372 is inserted into the set. Otherwise, the functor \p func is called with the item found.
373 The functor \p Func signature is:
376 void operator()( bool bNew, value_type& item, const Q& val );
381 - \p bNew - \p true if the item has been inserted, \p false otherwise
382 - \p item - item of the set
383 - \p val - argument \p key passed into the \p ensure function
385 The functor may change non-key fields of the \p item.
387 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
388 \p second is true if new item has been added or \p false if the item with \p key
389 already is in the set.
391 @warning For \ref cds_nonintrusive_MichaelList_gc "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
392 \ref cds_nonintrusive_LazyList_gc "LazyList" provides exclusive access to inserted item and does not require any node-level
395 template <typename Q, typename Func>
396 std::pair<bool, bool> ensure( const Q& val, Func func )
398 std::pair<bool, bool> bRet = bucket( val ).ensure( val, func );
399 if ( bRet.first && bRet.second )
404 /// Inserts data of type \p value_type constructed from \p args
406 Returns \p true if inserting successful, \p false otherwise.
408 template <typename... Args>
409 bool emplace( Args&&... args )
411 bool bRet = bucket( value_type(std::forward<Args>(args)...) ).emplace( std::forward<Args>(args)... );
417 /// Deletes \p key from the set
418 /** \anchor cds_nonintrusive_MichaelSet_erase_val
420 Since the key of MichaelHashSet's item type \ref value_type is not explicitly specified,
421 template parameter \p Q defines the key type searching in the list.
422 The set item comparator should be able to compare the type \p value_type
425 Return \p true if key is found and deleted, \p false otherwise
427 template <typename Q>
428 bool erase( Q const& key )
430 const bool bRet = bucket( key ).erase( key );
436 /// Deletes the item from the set using \p pred predicate for searching
438 The function is an analog of \ref cds_nonintrusive_MichaelSet_erase_val "erase(Q const&)"
439 but \p pred is used for key comparing.
440 \p Less functor has the interface like \p std::less.
441 \p Less must imply the same element order as the comparator used for building the set.
443 template <typename Q, typename Less>
444 bool erase_with( Q const& key, Less pred )
446 const bool bRet = bucket( key ).erase_with( key, pred );
452 /// Deletes \p key from the set
453 /** \anchor cds_nonintrusive_MichaelSet_erase_func
455 The function searches an item with key \p key, calls \p f functor
456 and deletes the item. If \p key is not found, the functor is not called.
458 The functor \p Func interface:
461 void operator()(value_type& item);
464 where \p item - the item found.
466 Since the key of %MichaelHashSet's \p value_type is not explicitly specified,
467 template parameter \p Q defines the key type searching in the list.
468 The list item comparator should be able to compare the type \p T of list item
471 Return \p true if key is found and deleted, \p false otherwise
473 template <typename Q, typename Func>
474 bool erase( Q const& key, Func f )
476 const bool bRet = bucket( key ).erase( key, f );
482 /// Deletes the item from the set using \p pred predicate for searching
484 The function is an analog of \ref cds_nonintrusive_MichaelSet_erase_func "erase(Q const&, Func)"
485 but \p pred is used for key comparing.
486 \p Less functor has the interface like \p std::less.
487 \p Less must imply the same element order as the comparator used for building the set.
489 template <typename Q, typename Less, typename Func>
490 bool erase_with( Q const& key, Less pred, Func f )
492 const bool bRet = bucket( key ).erase_with( key, pred, f );
498 /// Extracts the item with specified \p key
499 /** \anchor cds_nonintrusive_MichaelHashSet_hp_extract
500 The function searches an item with key equal to \p key,
501 unlinks it from the set, and returns it in \p dest parameter.
502 If the item with key equal to \p key is not found the function returns \p false.
504 Note the compare functor should accept a parameter of type \p Q that may be not the same as \p value_type.
506 The extracted item is freed automatically when returned \ref guarded_ptr object will be destroyed or released.
507 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
511 typedef cds::container::MichaelHashSet< your_template_args > michael_set;
515 michael_set::guarded_ptr gp;
516 theSet.extract( gp, 5 );
520 // Destructor of gp releases internal HP guard
524 template <typename Q>
525 bool extract( guarded_ptr& dest, Q const& key )
527 const bool bRet = bucket( key ).extract( dest, key );
533 /// Extracts the item using compare functor \p pred
535 The function is an analog of \ref cds_nonintrusive_MichaelHashSet_hp_extract "extract(guarded_ptr&, Q const&)"
536 but \p pred predicate is used for key comparing.
538 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
540 \p pred must imply the same element order as the comparator used for building the set.
542 template <typename Q, typename Less>
543 bool extract_with( guarded_ptr& dest, Q const& key, Less pred )
545 const bool bRet = bucket( key ).extract_with( dest, key, pred );
551 /// Finds the key \p key
552 /** \anchor cds_nonintrusive_MichaelSet_find_func
554 The function searches the item with key equal to \p key and calls the functor \p f for item found.
555 The interface of \p Func functor is:
558 void operator()( value_type& item, Q& key );
561 where \p item is the item found, \p key is the <tt>find</tt> function argument.
563 You may pass \p f argument by reference using \p std::ref.
565 The functor may change non-key fields of \p item. Note that the functor is only guarantee
566 that \p item cannot be disposed during functor is executing.
567 The functor does not serialize simultaneous access to the set's \p item. If such access is
568 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
570 The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
571 can modify both arguments.
573 Note the hash functor specified for class \p Traits template parameter
574 should accept a parameter of type \p Q that may be not the same as \p value_type.
576 The function returns \p true if \p key is found, \p false otherwise.
578 template <typename Q, typename Func>
579 bool find( Q& key, Func f )
581 return bucket( key ).find( key, f );
584 /// Finds the key \p key using \p pred predicate for searching
586 The function is an analog of \ref cds_nonintrusive_MichaelSet_find_func "find(Q&, Func)"
587 but \p pred is used for key comparing.
588 \p Less functor has the interface like \p std::less.
589 \p Less must imply the same element order as the comparator used for building the set.
591 template <typename Q, typename Less, typename Func>
592 bool find_with( Q& key, Less pred, Func f )
594 return bucket( key ).find_with( key, pred, f );
597 /// Finds the key \p key
598 /** \anchor cds_nonintrusive_MichaelSet_find_val
599 The function searches the item with key equal to \p key
600 and returns \p true if it is found, and \p false otherwise.
602 Note the hash functor specified for class \p Traits template parameter
603 should accept a parameter of type \p Q that may be not the same as \ref value_type.
605 template <typename Q>
606 bool find( Q const& key )
608 return bucket( key ).find( key );
611 /// Finds the key \p key using \p pred predicate for searching
613 The function is an analog of \ref cds_nonintrusive_MichaelSet_find_val "find(Q const&)"
614 but \p pred is used for key comparing.
615 \p Less functor has the interface like \p std::less.
616 \p Less must imply the same element order as the comparator used for building the set.
618 template <typename Q, typename Less>
619 bool find_with( Q const& key, Less pred )
621 return bucket( key ).find_with( key, pred );
624 /// Finds the key \p key and return the item found
625 /** \anchor cds_nonintrusive_MichaelHashSet_hp_get
626 The function searches the item with key equal to \p key
627 and assigns the item found to guarded pointer \p ptr.
628 The function returns \p true if \p key is found, and \p false otherwise.
629 If \p key is not found the \p ptr parameter is not changed.
631 @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
635 typedef cds::container::MichaeHashSet< your_template_params > michael_set;
639 michael_set::guarded_ptr gp;
640 if ( theSet.get( gp, 5 )) {
644 // Destructor of guarded_ptr releases internal HP guard
648 Note the compare functor specified for \p OrderedList template parameter
649 should accept a parameter of type \p Q that can be not the same as \p value_type.
651 template <typename Q>
652 bool get( guarded_ptr& ptr, Q const& key )
654 return bucket( key ).get( ptr, key );
657 /// Finds the key \p key and return the item found
659 The function is an analog of \ref cds_nonintrusive_MichaelHashSet_hp_get "get( guarded_ptr& ptr, Q const&)"
660 but \p pred is used for comparing the keys.
662 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
664 \p pred must imply the same element order as the comparator used for building the set.
666 template <typename Q, typename Less>
667 bool get_with( guarded_ptr& ptr, Q const& key, Less pred )
669 return bucket( key ).get_with( ptr, key, pred );
672 /// Clears the set (non-atomic)
674 The function erases all items from the set.
676 The function is not atomic. It cleans up each bucket and then resets the item counter to zero.
677 If there are a thread that performs insertion while \p clear is working the result is undefined in general case:
678 <tt> empty() </tt> may return \p true but the set may contain item(s).
679 Therefore, \p clear may be used only for debugging purposes.
683 for ( size_t i = 0; i < bucket_count(); ++i )
684 m_Buckets[i].clear();
685 m_ItemCounter.reset();
688 /// Checks if the set is empty
690 Emptiness is checked by item counting: if item count is zero then the set is empty.
691 Thus, the correct item counting feature is an important part of Michael's set implementation.
698 /// Returns item count in the set
701 return m_ItemCounter;
704 /// Returns the size of hash table
706 Since MichaelHashSet cannot dynamically extend the hash table size,
707 the value returned is an constant depending on object initialization parameters;
708 see MichaelHashSet::MichaelHashSet for explanation.
710 size_t bucket_count() const
712 return m_nHashBitmask + 1;
716 }} // namespace cds::container
718 #endif // ifndef __CDS_CONTAINER_MICHAEL_SET_H