2 This file is a part of libcds - Concurrent Data Structures library
4 (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
6 Source code repo: http://github.com/khizmax/libcds/
7 Download: http://sourceforge.net/projects/libcds/files/
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions are met:
12 * Redistributions of source code must retain the above copyright notice, this
13 list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 this list of conditions and the following disclaimer in the documentation
17 and/or other materials provided with the distribution.
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #ifndef CDSLIB_CONTAINER_MICHAEL_SET_RCU_H
32 #define CDSLIB_CONTAINER_MICHAEL_SET_RCU_H
34 #include <cds/container/details/michael_set_base.h>
35 #include <cds/details/allocator.h>
37 namespace cds { namespace container {
39 /// Michael's hash set (template specialization for \ref cds_urcu_desc "RCU")
40 /** @ingroup cds_nonintrusive_set
41 \anchor cds_nonintrusive_MichaelHashSet_rcu
44 - [2002] Maged Michael "High performance dynamic lock-free hash tables and list-based sets"
46 Michael's hash table algorithm is based on lock-free ordered list and it is very simple.
47 The main structure is an array \p T of size \p M. Each element in \p T is basically a pointer
48 to a hash bucket, implemented as a singly linked list. The array of buckets cannot be dynamically expanded.
49 However, each bucket may contain unbounded number of items.
51 Template parameters are:
52 - \p RCU - one of \ref cds_urcu_gc "RCU type"
53 - \p OrderedList - ordered list implementation used as the bucket for hash set, for example,
54 \ref cds_nonintrusive_MichaelList_rcu "MichaelList".
55 The ordered list implementation specifies the type \p T stored in the hash-set,
56 the comparison functor for the type \p T and other features specific for
58 - \p Traits - set traits, default is michael_set::traits.
59 Instead of defining \p Traits struct you may use option-based syntax with michael_set::make_traits metafunction.
61 About hash functor see \ref cds_nonintrusive_MichaelHashSet_hash_functor "MichaelSet hash functor".
65 Suppose, we have the following type \p Foo that we want to store in your \p %MichaelHashSet:
68 int nKey ; // key field
69 int nVal ; // value field
73 To use \p %MichaelHashSet for \p Foo values, you should first choose suitable ordered list class
74 that will be used as a bucket for the set. We will cds::urcu::general_buffered<> RCU type and
75 MichaelList as a bucket type.
76 You should include RCU-related header file (<tt>cds/urcu/general_buffered.h</tt> in this example)
77 before including <tt>cds/container/michael_set_rcu.h</tt>.
78 Also, for ordered list we should develop a comparator for our \p Foo struct.
80 #include <cds/urcu/general_buffered.h>
81 #include <cds/container/michael_list_rcu.h>
82 #include <cds/container/michael_set_rcu.h>
84 namespace cc = cds::container;
88 int operator ()(Foo const& v1, Foo const& v2 ) const
90 if ( std::less( v1.nKey, v2.nKey ))
92 return std::less(v2.nKey, v1.nKey) ? 1 : 0;
97 typedef cc::MichaelList< cds::urcu::gc< cds::urcu::general_buffered<> >, Foo,
98 typename cc::michael_list::make_traits<
99 cc::opt::compare< Foo_cmp > // item comparator option
103 // Hash functor for Foo
105 size_t operator ()( int i ) const
107 return std::hash( i );
109 size_t operator()( Foo const& i ) const
111 return std::hash( i.nKey );
116 // Note that \p RCU template parameter of ordered list must be equal \p RCU for the set.
117 typedef cc::MichaelHashSet< cds::urcu::gc< cds::urcu::general_buffered<> >, bucket_list,
118 cc::michael_set::make_traits<
119 cc::opt::hash< foo_hash >
129 #ifdef CDS_DOXYGEN_INVOKED
130 class Traits = michael_set::traits
135 class MichaelHashSet< cds::urcu::gc< RCU >, OrderedList, Traits >
138 typedef cds::urcu::gc< RCU > gc; ///< RCU used as garbage collector
139 typedef OrderedList bucket_type; ///< type of ordered list to be used as a bucket implementation
140 typedef Traits traits; ///< Set traits
142 typedef typename bucket_type::value_type value_type; ///< type of value to be stored in the list
143 typedef typename bucket_type::key_comparator key_comparator; ///< key comparing functor
145 /// Hash functor for \ref value_type and all its derivatives that you use
146 typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
147 typedef typename traits::item_counter item_counter; ///< Item counter type
149 /// Bucket table allocator
150 typedef cds::details::Allocator< bucket_type, typename traits::allocator > bucket_table_allocator;
152 typedef typename bucket_type::rcu_lock rcu_lock; ///< RCU scoped lock
153 typedef typename bucket_type::exempt_ptr exempt_ptr; ///< pointer to extracted node
154 typedef typename bucket_type::raw_ptr raw_ptr; ///< Return type of \p get() member function and its derivatives
155 /// Group of \p extract_xxx functions require external locking if underlying ordered list requires that
156 static CDS_CONSTEXPR const bool c_bExtractLockExternal = bucket_type::c_bExtractLockExternal;
159 item_counter m_ItemCounter; ///< Item counter
160 hash m_HashFunctor; ///< Hash functor
161 bucket_type * m_Buckets; ///< bucket table
165 const size_t m_nHashBitmask;
170 /// Calculates hash value of \p key
171 template <typename Q>
172 size_t hash_value( Q const& key ) const
174 return m_HashFunctor( key ) & m_nHashBitmask;
177 /// Returns the bucket (ordered list) for \p key
178 template <typename Q>
179 bucket_type& bucket( Q const& key )
181 return m_Buckets[ hash_value( key ) ];
183 template <typename Q>
184 bucket_type const& bucket( Q const& key ) const
186 return m_Buckets[ hash_value( key ) ];
192 The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
193 - it has no post-increment operator
194 - it iterates items in unordered fashion
195 - The iterator cannot be moved across thread boundary since it may contain GC's guard that is thread-private GC data.
196 - Iterator ensures thread-safety even if you delete the item that iterator points to. However, in case of concurrent
197 deleting operations it is no guarantee that you iterate all item in the set.
199 Therefore, the use of iterators in concurrent environment is not good idea. Use the iterator for the concurrent container
200 for debug purpose only.
202 typedef michael_set::details::iterator< bucket_type, false > iterator;
204 /// Const forward iterator
205 typedef michael_set::details::iterator< bucket_type, true > const_iterator;
207 /// Returns a forward iterator addressing the first element in a set
209 For empty set \code begin() == end() \endcode
213 return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
216 /// Returns an iterator that addresses the location succeeding the last element in a set
218 Do not use the value returned by <tt>end</tt> function to access any item.
219 The returned value can be used only to control reaching the end of the set.
220 For empty set \code begin() == end() \endcode
224 return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
227 /// Returns a forward const iterator addressing the first element in a set
229 const_iterator begin() const
231 return get_const_begin();
233 const_iterator cbegin() const
235 return get_const_begin();
239 /// Returns an const iterator that addresses the location succeeding the last element in a set
241 const_iterator end() const
243 return get_const_end();
245 const_iterator cend() const
247 return get_const_end();
253 const_iterator get_const_begin() const
255 return const_iterator( const_cast<bucket_type const&>(m_Buckets[0]).begin(), m_Buckets, m_Buckets + bucket_count() );
257 const_iterator get_const_end() const
259 return const_iterator( const_cast<bucket_type const&>(m_Buckets[bucket_count() - 1]).end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
264 /// Initialize hash set
266 The Michael's hash set is non-expandable container. You should point the average count of items \p nMaxItemCount
267 when you create an object.
268 \p nLoadFactor parameter defines average count of items per bucket and it should be small number between 1 and 10.
269 Remember, since the bucket implementation is an ordered list, searching in the bucket is linear [<tt>O(nLoadFactor)</tt>].
271 The ctor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
274 size_t nMaxItemCount, ///< estimation of max item count in the hash set
275 size_t nLoadFactor ///< load factor: estimation of max number of items in the bucket
276 ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
278 // GC and OrderedList::gc must be the same
279 static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
281 // atomicity::empty_item_counter is not allowed as a item counter
282 static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
283 "atomicity::empty_item_counter is not allowed as a item counter");
285 m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
288 /// Clears hash set and destroys it
292 bucket_table_allocator().Delete( m_Buckets, bucket_count() );
297 The function creates a node with copy of \p val value
298 and then inserts the node created into the set.
300 The type \p Q should contain as minimum the complete key for the node.
301 The object of \ref value_type should be constructible from a value of type \p Q.
302 In trivial case, \p Q is equal to \ref value_type.
304 The function applies RCU lock internally.
306 Returns \p true if \p val is inserted into the set, \p false otherwise.
308 template <typename Q>
309 bool insert( Q const& val )
311 const bool bRet = bucket( val ).insert( val );
319 The function allows to split creating of new item into two part:
320 - create item with key only
321 - insert new item into the set
322 - if inserting is success, calls \p f functor to initialize value-fields of \p val.
324 The functor signature is:
326 void func( value_type& val );
328 where \p val is the item inserted.
329 The user-defined functor is called only if the inserting is success.
331 The function applies RCU lock internally.
333 @warning For \ref cds_nonintrusive_MichaelList_rcu "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
334 \ref cds_nonintrusive_LazyList_rcu "LazyList" provides exclusive access to inserted item and does not require any node-level
337 template <typename Q, typename Func>
338 bool insert( Q const& val, Func f )
340 const bool bRet = bucket( val ).insert( val, f );
346 /// Ensures that the item exists in the set
348 The operation performs inserting or changing data with lock-free manner.
350 If the \p val key not found in the set, then the new item created from \p val
351 is inserted into the set. Otherwise, the functor \p func is called with the item found.
352 The functor \p Func signature is:
355 void operator()( bool bNew, value_type& item, const Q& val );
360 - \p bNew - \p true if the item has been inserted, \p false otherwise
361 - \p item - item of the set
362 - \p val - argument \p key passed into the \p ensure function
364 The functor may change non-key fields of the \p item.
366 The function applies RCU lock internally.
368 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
369 \p second is true if new item has been added or \p false if the item with \p key
370 already is in the set.
372 @warning For \ref cds_nonintrusive_MichaelList_rcu "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
373 \ref cds_nonintrusive_LazyList_rcu "LazyList" provides exclusive access to inserted item and does not require any node-level
376 /// Updates the element
378 The operation performs inserting or changing data with lock-free manner.
380 If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
381 Otherwise, the functor \p func is called with item found.
382 The functor signature is:
385 void operator()( bool bNew, value_type& item, Q const& val );
389 - \p bNew - \p true if the item has been inserted, \p false otherwise
390 - \p item - item of the set
391 - \p val - argument \p val passed into the \p %update() function
393 The functor may change non-key fields of the \p item.
395 The function applies RCU lock internally.
397 Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successfull,
398 \p second is \p true if new item has been added or \p false if the item with \p key
399 already is in the set.
401 @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
402 \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
405 template <typename Q, typename Func>
406 std::pair<bool, bool> update( const Q& val, Func func, bool bAllowInsert = true )
408 std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowInsert );
413 template <typename Q, typename Func>
414 CDS_DEPRECATED("ensure() is deprecated, use update()")
415 std::pair<bool, bool> ensure( const Q& val, Func func )
417 return update( val, func, true );
421 /// Inserts data of type \p value_type created from \p args
423 Returns \p true if inserting successful, \p false otherwise.
425 The function applies RCU lock internally.
427 template <typename... Args>
428 bool emplace( Args&&... args )
430 bool bRet = bucket( value_type(std::forward<Args>(args)...) ).emplace( std::forward<Args>(args)... );
436 /// Deletes \p key from the set
437 /** \anchor cds_nonintrusive_MichealSet_rcu_erase_val
439 Since the key of MichaelHashSet's item type \p value_type is not explicitly specified,
440 template parameter \p Q defines the key type searching in the list.
441 The set item comparator should be able to compare the type \p value_type
444 RCU \p synchronize method can be called. RCU should not be locked.
446 Return \p true if key is found and deleted, \p false otherwise
448 template <typename Q>
449 bool erase( Q const& key )
451 const bool bRet = bucket( key ).erase( key );
457 /// Deletes the item from the set using \p pred predicate for searching
459 The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_erase_val "erase(Q const&)"
460 but \p pred is used for key comparing.
461 \p Less functor has the interface like \p std::less.
462 \p Less must imply the same element order as the comparator used for building the set.
464 template <typename Q, typename Less>
465 bool erase_with( Q const& key, Less pred )
467 const bool bRet = bucket( key ).erase_with( key, pred );
473 /// Deletes \p key from the set
474 /** \anchor cds_nonintrusive_MichealSet_rcu_erase_func
476 The function searches an item with key \p key, calls \p f functor
477 and deletes the item. If \p key is not found, the functor is not called.
479 The functor \p Func interface:
482 void operator()(value_type const& val);
486 Since the key of %MichaelHashSet's \p value_type is not explicitly specified,
487 template parameter \p Q defines the key type searching in the list.
488 The list item comparator should be able to compare the type \p T of list item
491 RCU \p synchronize method can be called. RCU should not be locked.
493 Return \p true if key is found and deleted, \p false otherwise
495 template <typename Q, typename Func>
496 bool erase( Q const& key, Func f )
498 const bool bRet = bucket( key ).erase( key, f );
504 /// Deletes the item from the set using \p pred predicate for searching
506 The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_erase_func "erase(Q const&, Func)"
507 but \p pred is used for key comparing.
508 \p Less functor has the interface like \p std::less.
509 \p Less must imply the same element order as the comparator used for building the set.
511 template <typename Q, typename Less, typename Func>
512 bool erase_with( Q const& key, Less pred, Func f )
514 const bool bRet = bucket( key ).erase_with( key, pred, f );
520 /// Extracts an item from the set
521 /** \anchor cds_nonintrusive_MichaelHashSet_rcu_extract
522 The function searches an item with key equal to \p key in the set,
523 unlinks it from the set, and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the item found.
524 If the item with the key equal to \p key is not found the function return an empty \p exempt_ptr.
526 The function just excludes the item from the set and returns a pointer to item found.
527 Depends on \p bucket_type you should or should not lock RCU before calling of this function:
528 - for the set based on \ref cds_nonintrusive_MichaelList_rcu "MichaelList" RCU should not be locked
529 - for the set based on \ref cds_nonintrusive_LazyList_rcu "LazyList" RCU should be locked
530 See ordered list implementation for details.
533 #include <cds/urcu/general_buffered.h>
534 #include <cds/container/michael_list_rcu.h>
535 #include <cds/container/michael_set_rcu.h>
537 typedef cds::urcu::gc< general_buffered<> > rcu;
538 typedef cds::container::MichaelList< rcu, Foo > rcu_michael_list;
539 typedef cds::container::MichaelHashSet< rcu, rcu_michael_list, foo_traits > rcu_michael_set;
541 rcu_michael_set theSet;
544 typename rcu_michael_set::exempt_ptr p;
546 // For MichaelList we should not lock RCU
548 // Note that you must not delete the item found inside the RCU lock
549 p = theSet.extract( 10 );
551 // do something with p
555 // We may safely release p here
556 // release() passes the pointer to RCU reclamation cycle
560 template <typename Q>
561 exempt_ptr extract( Q const& key )
563 exempt_ptr p = bucket( key ).extract( key );
569 /// Extracts an item from the set using \p pred predicate for searching
571 The function is an analog of \p extract(Q const&) but \p pred is used for key comparing.
572 \p Less functor has the interface like \p std::less.
573 \p pred must imply the same element order as the comparator used for building the set.
575 template <typename Q, typename Less>
576 exempt_ptr extract_with( Q const& key, Less pred )
578 exempt_ptr p = bucket( key ).extract_with( key, pred );
584 /// Finds the key \p key
585 /** \anchor cds_nonintrusive_MichealSet_rcu_find_func
587 The function searches the item with key equal to \p key and calls the functor \p f for item found.
588 The interface of \p Func functor is:
591 void operator()( value_type& item, Q& key );
594 where \p item is the item found, \p key is the <tt>find</tt> function argument.
596 The functor may change non-key fields of \p item. Note that the functor is only guarantee
597 that \p item cannot be disposed during functor is executing.
598 The functor does not serialize simultaneous access to the set's \p item. If such access is
599 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
601 The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
602 can modify both arguments.
604 Note the hash functor specified for class \p Traits template parameter
605 should accept a parameter of type \p Q that may be not the same as \p value_type.
607 The function applies RCU lock internally.
609 The function returns \p true if \p key is found, \p false otherwise.
611 template <typename Q, typename Func>
612 bool find( Q& key, Func f )
614 return bucket( key ).find( key, f );
617 template <typename Q, typename Func>
618 bool find( Q const& key, Func f )
620 return bucket( key ).find( key, f );
624 /// Finds the key \p key using \p pred predicate for searching
626 The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_find_func "find(Q&, Func)"
627 but \p pred is used for key comparing.
628 \p Less functor has the interface like \p std::less.
629 \p Less must imply the same element order as the comparator used for building the set.
631 template <typename Q, typename Less, typename Func>
632 bool find_with( Q& key, Less pred, Func f )
634 return bucket( key ).find_with( key, pred, f );
637 template <typename Q, typename Less, typename Func>
638 bool find_with( Q const& key, Less pred, Func f )
640 return bucket( key ).find_with( key, pred, f );
644 /// Checks whether the set contains \p key
647 The function searches the item with key equal to \p key
648 and returns \p true if the key is found, and \p false otherwise.
650 Note the hash functor specified for class \p Traits template parameter
651 should accept a parameter of type \p Q that can be not the same as \p value_type.
653 template <typename Q>
654 bool contains( Q const& key )
656 return bucket( key ).contains( key );
659 template <typename Q>
660 CDS_DEPRECATED("use contains()")
661 bool find( Q const& key )
663 return contains( key );
667 /// Checks whether the set contains \p key using \p pred predicate for searching
669 The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
670 \p Less functor has the interface like \p std::less.
671 \p Less must imply the same element order as the comparator used for building the set.
673 template <typename Q, typename Less>
674 bool contains( Q const& key, Less pred )
676 return bucket( key ).contains( key, pred );
679 template <typename Q, typename Less>
680 CDS_DEPRECATED("use contains()")
681 bool find_with( Q const& key, Less pred )
683 return contains( key, pred );
687 /// Finds the key \p key and return the item found
688 /** \anchor cds_nonintrusive_MichaelHashSet_rcu_get
689 The function searches the item with key equal to \p key and returns the pointer to item found.
690 If \p key is not found it returns \p nullptr.
691 Note the type of returned value depends on underlying \p bucket_type.
692 For details, see documentation of ordered list you use.
694 Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
696 RCU should be locked before call of this function.
697 Returned item is valid only while RCU is locked:
699 typedef cds::container::MichaelHashSet< your_template_parameters > hash_set;
701 typename hash_set::raw_ptr gp;
705 hash_set::rcu_lock lock;
707 gp = theSet.get( 5 );
712 // Unlock RCU by rcu_lock destructor
713 // gp can be reclaimed at any time after RCU has been unlocked
717 template <typename Q>
718 raw_ptr get( Q const& key )
720 return bucket( key ).get( key );
723 /// Finds the key \p key and return the item found
725 The function is an analog of \ref cds_nonintrusive_MichaelHashSet_rcu_get "get(Q const&)"
726 but \p pred is used for comparing the keys.
728 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
730 \p pred must imply the same element order as the comparator used for building the set.
732 template <typename Q, typename Less>
733 raw_ptr get_with( Q const& key, Less pred )
735 return bucket( key ).get_with( key, pred );
738 /// Clears the set (not atomic)
741 for ( size_t i = 0; i < bucket_count(); ++i )
742 m_Buckets[i].clear();
743 m_ItemCounter.reset();
746 /// Checks if the set is empty
748 Emptiness is checked by item counting: if item count is zero then the set is empty.
749 Thus, the correct item counting feature is an important part of Michael's set implementation.
756 /// Returns item count in the set
759 return m_ItemCounter;
762 /// Returns the size of hash table
764 Since \p %MichaelHashSet cannot dynamically extend the hash table size,
765 the value returned is an constant depending on object initialization parameters;
766 see MichaelHashSet::MichaelHashSet for explanation.
768 size_t bucket_count() const
770 return m_nHashBitmask + 1;
774 }} // namespace cds::container
776 #endif // ifndef CDSLIB_CONTAINER_MICHAEL_SET_RCU_H