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_INTRUSIVE_SPLIT_LIST_H
32 #define CDSLIB_INTRUSIVE_SPLIT_LIST_H
35 #include <cds/intrusive/details/split_list_base.h>
36 #include <cds/details/type_padding.h>
38 namespace cds { namespace intrusive {
40 /// Split-ordered list
41 /** @ingroup cds_intrusive_map
42 \anchor cds_intrusive_SplitListSet_hp
44 Hash table implementation based on split-ordered list algorithm discovered by Ori Shalev and Nir Shavit, see
45 - [2003] Ori Shalev, Nir Shavit "Split-Ordered Lists - Lock-free Resizable Hash Tables"
46 - [2008] Nir Shavit "The Art of Multiprocessor Programming"
48 The split-ordered list is a lock-free implementation of an extensible unbounded hash table. It uses original
49 recursive split-ordering algorithm discovered by Ori Shalev and Nir Shavit that allows to split buckets
50 without item moving on resizing.
52 \anchor cds_SplitList_algo_desc
53 <b>Short description</b>
54 [from [2003] Ori Shalev, Nir Shavit "Split-Ordered Lists - Lock-free Resizable Hash Tables"]
56 The algorithm keeps all the items in one lock-free linked list, and gradually assigns the bucket pointers to
57 the places in the list where a sublist of 'correct' items can be found. A bucket is initialized upon first
58 access by assigning it to a new 'dummy' node (dashed contour) in the list, preceding all items that should be
59 in that bucket. A newly created bucket splits an older bucket's chain, reducing the access cost to its items. The
60 table uses a modulo 2**i hash (there are known techniques for 'pre-hashing' before a modulo 2**i hash
61 to overcome possible binary correlations among values). The table starts at size 2 and repeatedly doubles in size.
63 Unlike moving an item, the operation of directing a bucket pointer can be done
64 in a single CAS operation, and since items are not moved, they are never 'lost'.
65 However, to make this approach work, one must be able to keep the items in the
66 list sorted in such a way that any bucket's sublist can be 'split' by directing a new
67 bucket pointer within it. This operation must be recursively repeatable, as every
68 split bucket may be split again and again as the hash table grows. To achieve this
69 goal the authors introduced recursive split-ordering, a new ordering on keys that keeps items
70 in a given bucket adjacent in the list throughout the repeated splitting process.
72 Magically, yet perhaps not surprisingly, recursive split-ordering is achieved by
73 simple binary reversal: reversing the bits of the hash key so that the new key's
74 most significant bits (MSB) are those that were originally its least significant.
75 The split-order keys of regular nodes are exactly the bit-reverse image of the original
76 keys after turning on their MSB. For example, items 9 and 13 are in the <tt>1 mod
77 4</tt> bucket, which can be recursively split in two by inserting a new node between
80 To insert (respectively delete or search for) an item in the hash table, hash its
81 key to the appropriate bucket using recursive split-ordering, follow the pointer to
82 the appropriate location in the sorted items list, and traverse the list until the key's
83 proper location in the split-ordering (respectively until the key or a key indicating
84 the item is not in the list is found). Because of the combinatorial structure induced
85 by the split-ordering, this will require traversal of no more than an expected constant number of items.
87 The design is modular: to implement the ordered items list, you can use one of several
88 non-blocking list-based set algorithms: MichaelList, LazyList.
92 Template parameters are:
93 - \p GC - Garbage collector. Note the \p GC must be the same as the \p GC used for \p OrderedList
94 - \p OrderedList - ordered list implementation used as a bucket for hash set, for example, \p MichaelList, \p LazyList.
95 The intrusive ordered list implementation specifies the type \p T stored in the split-list set, the reclamation
96 schema \p GC used by split-list set, the comparison functor for the type \p T and other features specific for
98 - \p Traits - split-list traits, default is \p split_list::traits.
99 Instead of defining \p Traits struct you may use option-based syntax with \p split_list::make_traits metafunction.
101 @warning \p IterableList is not supported as \p OrderedList template parameter.
103 There are several specialization of the split-list class for different \p GC:
104 - for \ref cds_urcu_gc "RCU type" include <tt><cds/intrusive/split_list_rcu.h></tt> - see
105 \ref cds_intrusive_SplitListSet_rcu "RCU-based split-list"
106 - for cds::gc::nogc include <tt><cds/intrusive/split_list_nogc.h></tt> - see
107 \ref cds_intrusive_SplitListSet_nogc "persistent SplitListSet".
109 \anchor cds_SplitList_hash_functor
112 Some member functions of split-ordered list accept the key parameter of type \p Q which differs from \p value_type.
113 It is expected that type \p Q contains full key of \p value_type, and for equal keys of type \p Q and \p value_type
114 the hash values of these keys must be equal too.
115 The hash functor \p Traits::hash should accept parameters of both type:
119 std::string key_ ; // key field
125 size_t operator()( const std::string& s ) const
127 return std::hash( s );
130 size_t operator()( const Foo& f ) const
132 return (*this)( f.key_ );
139 First, you should choose ordered list type to use in your split-list set:
141 // For gc::HP-based MichaelList implementation
142 #include <cds/intrusive/michael_list_hp.h>
144 // cds::intrusive::SplitListSet declaration
145 #include <cds/intrusive/split_list.h>
148 // Note you should declare your struct based on cds::intrusive::split_list::node
149 // which is a wrapper for ordered-list node struct.
150 // In our case, the node type for HP-based MichaelList is cds::intrusive::michael_list::node< cds::gc::HP >
151 struct Foo: public cds::intrusive::split_list::node< cds::intrusive::michael_list::node< cds::gc::HP > >
153 std::string key_ ; // key field
154 unsigned val_ ; // value field
155 // ... other value fields
158 // Declare comparator for the item
161 int operator()( const Foo& f1, const Foo& f2 ) const
163 return f1.key_.compare( f2.key_ );
167 // Declare base ordered-list type for split-list
168 typedef cds::intrusive::MichaelList< cds::gc::HP, Foo,
169 typename cds::intrusive::michael_list::make_traits<
171 cds::intrusive::opt::hook< cds::intrusive::michael_list::base_hook< cds::opt::gc< cds::gc::HP > > >
172 // item comparator option
173 ,cds::opt::compare< FooCmp >
178 Second, you should declare split-list set container:
181 // Declare hash functor
182 // Note, the hash functor accepts parameter type Foo and std::string
184 size_t operator()( const Foo& f ) const
186 return cds::opt::v::hash<std::string>()( f.key_ );
188 size_t operator()( const std::string& s ) const
190 return cds::opt::v::hash<std::string>()( s );
194 // Split-list set typedef
195 typedef cds::intrusive::SplitListSet<
198 ,typename cds::intrusive::split_list::make_traits<
199 cds::opt::hash< FooHash >
204 Now, you can use \p Foo_set in your application.
210 fooSet.insert( *foo );
218 # ifdef CDS_DOXYGEN_INVOKED
219 class Traits = split_list::traits
227 typedef GC gc; ///< Garbage collector
228 typedef Traits traits; ///< Set traits
232 typedef split_list::details::rebind_list_traits<OrderedList, traits> wrapped_ordered_list;
236 # ifdef CDS_DOXYGEN_INVOKED
237 typedef OrderedList ordered_list; ///< type of ordered list used as a base for split-list
239 typedef typename wrapped_ordered_list::result ordered_list;
241 typedef typename ordered_list::value_type value_type; ///< type of value stored in the split-list
242 typedef typename ordered_list::key_comparator key_comparator; ///< key comparison functor
243 typedef typename ordered_list::disposer disposer; ///< Node disposer functor
245 /// Hash functor for \p %value_type and all its derivatives that you use
246 typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
248 typedef typename traits::item_counter item_counter; ///< Item counter type
249 typedef typename traits::back_off back_off; ///< back-off strategy for spinning
250 typedef typename traits::memory_model memory_model; ///< Memory ordering. See cds::opt::memory_model option
251 typedef typename traits::stat stat; ///< Internal statistics, see \p spit_list::stat
252 typedef typename ordered_list::guarded_ptr guarded_ptr; ///< Guarded pointer
254 /// Count of hazard pointer required
255 static CDS_CONSTEXPR const size_t c_nHazardPtrCount = ordered_list::c_nHazardPtrCount + 4; // +4 - for iterators
259 typedef typename ordered_list::node_type list_node_type; ///< Node type as declared in ordered list
260 typedef split_list::node<list_node_type> node_type; ///< split-list node type
261 typedef node_type aux_node_type; ///< dummy node type
263 /// Split-list node traits
265 This traits is intended for converting between underlying ordered list node type \p list_node_type
266 and split-list node type \p node_type
268 typedef split_list::node_traits<typename ordered_list::node_traits> node_traits;
270 /// Bucket table implementation
271 typedef typename split_list::details::bucket_table_selector<
272 traits::dynamic_bucket_table
275 , opt::allocator< typename traits::allocator >
276 , opt::memory_model< memory_model >
277 , opt::free_list< typename traits::free_list >
278 >::type bucket_table;
283 /// Ordered list wrapper to access protected members
284 class ordered_list_wrapper: public ordered_list
286 typedef ordered_list base_class;
287 typedef typename base_class::auxiliary_head bucket_head_type;
290 bool insert_at( aux_node_type * pHead, value_type& val )
292 assert( pHead != nullptr );
293 bucket_head_type h(pHead);
294 return base_class::insert_at( h, val );
297 template <typename Func>
298 bool insert_at( aux_node_type * pHead, value_type& val, Func f )
300 assert( pHead != nullptr );
301 bucket_head_type h(pHead);
302 return base_class::insert_at( h, val, f );
305 template <typename Func>
306 std::pair<bool, bool> update_at( aux_node_type * pHead, value_type& val, Func func, bool bAllowInsert )
308 assert( pHead != nullptr );
309 bucket_head_type h(pHead);
310 return base_class::update_at( h, val, func, bAllowInsert );
313 bool unlink_at( aux_node_type * pHead, value_type& val )
315 assert( pHead != nullptr );
316 bucket_head_type h(pHead);
317 return base_class::unlink_at( h, val );
320 template <typename Q, typename Compare, typename Func>
321 bool erase_at( aux_node_type * pHead, split_list::details::search_value_type<Q> const& val, Compare cmp, Func f )
323 assert( pHead != nullptr );
324 bucket_head_type h(pHead);
325 return base_class::erase_at( h, val, cmp, f );
328 template <typename Q, typename Compare>
329 bool erase_at( aux_node_type * pHead, split_list::details::search_value_type<Q> const& val, Compare cmp )
331 assert( pHead != nullptr );
332 bucket_head_type h(pHead);
333 return base_class::erase_at( h, val, cmp );
336 template <typename Q, typename Compare>
337 guarded_ptr extract_at( aux_node_type * pHead, split_list::details::search_value_type<Q> const& val, Compare cmp )
339 assert( pHead != nullptr );
340 bucket_head_type h(pHead);
341 return base_class::extract_at( h, val, cmp );
344 template <typename Q, typename Compare, typename Func>
345 bool find_at( aux_node_type * pHead, split_list::details::search_value_type<Q>& val, Compare cmp, Func f )
347 assert( pHead != nullptr );
348 bucket_head_type h(pHead);
349 return base_class::find_at( h, val, cmp, f );
352 template <typename Q, typename Compare>
353 bool find_at( aux_node_type * pHead, split_list::details::search_value_type<Q> const& val, Compare cmp )
355 assert( pHead != nullptr );
356 bucket_head_type h(pHead);
357 return base_class::find_at( h, val, cmp );
360 template <typename Q, typename Compare>
361 guarded_ptr get_at( aux_node_type * pHead, split_list::details::search_value_type<Q> const& val, Compare cmp )
363 assert( pHead != nullptr );
364 bucket_head_type h(pHead);
365 return base_class::get_at( h, val, cmp );
368 bool insert_aux_node( aux_node_type * pNode )
370 return base_class::insert_aux_node( pNode );
372 bool insert_aux_node( aux_node_type * pHead, aux_node_type * pNode )
374 bucket_head_type h(pHead);
375 return base_class::insert_aux_node( h, pNode );
381 /// Initialize split-ordered list of default capacity
383 The default capacity is defined in bucket table constructor.
384 See \p split_list::expandable_bucket_table, \p split_list::static_bucket_table
385 which selects by \p split_list::dynamic_bucket_table option.
388 : m_nBucketCountLog2(1)
389 , m_nMaxItemCount( max_item_count(2, m_Buckets.load_factor()))
394 /// Initialize split-ordered list
396 size_t nItemCount ///< estimate average of item count
397 , size_t nLoadFactor = 1 ///< load factor - average item count per bucket. Small integer up to 8, default is 1.
399 : m_Buckets( nItemCount, nLoadFactor )
400 , m_nBucketCountLog2(1)
401 , m_nMaxItemCount( max_item_count(2, m_Buckets.load_factor()))
406 /// Destroys split-list set
409 // list contains aux node that cannot be retired
410 // all aux nodes will be destroyed by bucket table dtor
418 The function inserts \p val in the set if it does not contain
419 an item with key equal to \p val.
421 Returns \p true if \p val is placed into the set, \p false otherwise.
423 bool insert( value_type& val )
425 size_t nHash = hash_value( val );
426 aux_node_type * pHead = get_bucket( nHash );
427 assert( pHead != nullptr );
429 node_traits::to_node_ptr( val )->m_nHash = split_list::regular_hash( nHash );
431 if ( m_List.insert_at( pHead, val )) {
433 m_Stat.onInsertSuccess();
436 m_Stat.onInsertFailed();
442 This function is intended for derived non-intrusive containers.
444 The function allows to split creating of new item into two part:
445 - create item with key only
446 - insert new item into the set
447 - if inserting is success, calls \p f functor to initialize value-field of \p val.
449 The functor signature is:
451 void func( value_type& val );
453 where \p val is the item inserted.
454 The user-defined functor is called only if the inserting is success.
456 @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
457 \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
460 template <typename Func>
461 bool insert( value_type& val, Func f )
463 size_t nHash = hash_value( val );
464 aux_node_type * pHead = get_bucket( nHash );
465 assert( pHead != nullptr );
467 node_traits::to_node_ptr( val )->m_nHash = split_list::regular_hash( nHash );
469 if ( m_List.insert_at( pHead, val, f )) {
471 m_Stat.onInsertSuccess();
474 m_Stat.onInsertFailed();
480 The operation performs inserting or changing data with lock-free manner.
482 If the item \p val is not found in the set, then \p val is inserted
483 iff \p bAllowInsert is \p true.
484 Otherwise, the functor \p func is called with item found.
485 The functor signature is:
487 void func( bool bNew, value_type& item, value_type& val );
490 - \p bNew - \p true if the item has been inserted, \p false otherwise
491 - \p item - item of the set
492 - \p val - argument \p val passed into the \p update() function
493 If new item has been inserted (i.e. \p bNew is \p true) then \p item and \p val arguments
494 refers to the same thing.
496 The functor may change non-key fields of the \p item.
498 Returns std::pair<bool, bool> where \p first is \p true if operation is successful,
499 \p second is \p true if new item has been added or \p false if the item with \p val
500 already is in the list.
502 @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
503 \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
506 template <typename Func>
507 std::pair<bool, bool> update( value_type& val, Func func, bool bAllowInsert = true )
509 size_t nHash = hash_value( val );
510 aux_node_type * pHead = get_bucket( nHash );
511 assert( pHead != nullptr );
513 node_traits::to_node_ptr( val )->m_nHash = split_list::regular_hash( nHash );
515 std::pair<bool, bool> bRet = m_List.update_at( pHead, val, func, bAllowInsert );
516 if ( bRet.first && bRet.second ) {
518 m_Stat.onUpdateNew();
521 m_Stat.onUpdateExist();
525 template <typename Func>
526 CDS_DEPRECATED("ensure() is deprecated, use update()")
527 std::pair<bool, bool> ensure( value_type& val, Func func )
529 return update( val, func, true );
533 /// Unlinks the item \p val from the set
535 The function searches the item \p val in the set and unlinks it from the set
536 if it is found and is equal to \p val.
538 Difference between \ref erase and \p unlink functions: \p erase finds <i>a key</i>
539 and deletes the item found. \p unlink finds an item by key and deletes it
540 only if \p val is an item of that set, i.e. the pointer to item found
541 is equal to <tt> &val </tt>.
543 The function returns \p true if success and \p false otherwise.
545 bool unlink( value_type& val )
547 size_t nHash = hash_value( val );
548 aux_node_type * pHead = get_bucket( nHash );
549 assert( pHead != nullptr );
551 if ( m_List.unlink_at( pHead, val )) {
553 m_Stat.onEraseSuccess();
556 m_Stat.onEraseFailed();
560 /// Deletes the item from the set
561 /** \anchor cds_intrusive_SplitListSet_hp_erase
562 The function searches an item with key equal to \p key in the set,
563 unlinks it from the set, and returns \p true.
564 If the item with key equal to \p key is not found the function return \p false.
566 Difference between \ref erase and \p unlink functions: \p erase finds <i>a key</i>
567 and deletes the item found. \p unlink finds an item by key and deletes it
568 only if \p key is an item of that set, i.e. the pointer to item found
569 is equal to <tt> &key </tt>.
571 Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type.
573 template <typename Q>
574 bool erase( Q const& key )
576 return erase_( key, key_comparator());
579 /// Deletes the item from the set with comparing functor \p pred
582 The function is an analog of \ref cds_intrusive_SplitListSet_hp_erase "erase(Q const&)"
583 but \p pred predicate is used for key comparing.
584 \p Less has the interface like \p std::less.
585 \p pred must imply the same element order as the comparator used for building the set.
587 template <typename Q, typename Less>
588 bool erase_with( const Q& key, Less pred )
591 return erase_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>());
594 /// Deletes the item from the set
595 /** \anchor cds_intrusive_SplitListSet_hp_erase_func
596 The function searches an item with key equal to \p key in the set,
597 call \p f functor with item found, unlinks it from the set, and returns \p true.
598 The \ref disposer specified by \p OrderedList class template parameter is called
599 by garbage collector \p GC asynchronously.
601 The \p Func interface is
604 void operator()( value_type const& item );
608 If the item with key equal to \p key is not found the function return \p false.
610 Note the hash functor should accept a parameter of type \p Q that can be not the same as \p value_type.
612 template <typename Q, typename Func>
613 bool erase( Q const& key, Func f )
615 return erase_( key, key_comparator(), f );
618 /// Deletes the item from the set with comparing functor \p pred
620 The function is an analog of \ref cds_intrusive_SplitListSet_hp_erase_func "erase(Q const&, Func)"
621 but \p pred predicate is used for key comparing.
622 \p Less has the interface like \p std::less.
623 \p pred must imply the same element order as the comparator used for building the set.
625 template <typename Q, typename Less, typename Func>
626 bool erase_with( Q const& key, Less pred, Func f )
629 return erase_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>(), f );
632 /// Extracts the item with specified \p key
633 /** \anchor cds_intrusive_SplitListSet_hp_extract
634 The function searches an item with key equal to \p key,
635 unlinks it from the set, and returns it as \p guarded_ptr.
636 If \p key is not found the function returns an empty guarded pointer.
638 Note the compare functor should accept a parameter of type \p Q that may be not the same as \p value_type.
640 The \p disposer specified in \p OrderedList class' template parameter is called automatically
641 by garbage collector \p GC when returned \p guarded_ptr object will be destroyed or released.
642 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
646 typedef cds::intrusive::SplitListSet< your_template_args > splitlist_set;
647 splitlist_set theSet;
650 splitlist_set::guarded_ptr gp( theSet.extract( 5 ));
655 // Destructor of gp releases internal HP guard
659 template <typename Q>
660 guarded_ptr extract( Q const& key )
662 return extract_( key );
665 /// Extracts the item using compare functor \p pred
667 The function is an analog of \ref cds_intrusive_SplitListSet_hp_extract "extract(Q const&)"
668 but \p pred predicate is used for key comparing.
670 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
672 \p pred must imply the same element order as the comparator used for building the set.
674 template <typename Q, typename Less>
675 guarded_ptr extract_with( Q const& key, Less pred )
677 return extract_with_( key, pred );
680 /// Finds the key \p key
681 /** \anchor cds_intrusive_SplitListSet_hp_find_func
682 The function searches the item with key equal to \p key and calls the functor \p f for item found.
683 The interface of \p Func functor is:
686 void operator()( value_type& item, Q& key );
689 where \p item is the item found, \p key is the <tt>find</tt> function argument.
691 The functor can change non-key fields of \p item. Note that the functor is only guarantee
692 that \p item cannot be disposed during functor is executing.
693 The functor does not serialize simultaneous access to the set \p item. If such access is
694 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
696 Note the hash functor specified for class \p Traits template parameter
697 should accept a parameter of type \p Q that can be not the same as \p value_type.
699 The function returns \p true if \p key is found, \p false otherwise.
701 template <typename Q, typename Func>
702 bool find( Q& key, Func f )
704 return find_( key, key_comparator(), f );
707 template <typename Q, typename Func>
708 bool find( Q const& key, Func f )
710 return find_( key, key_comparator(), f );
714 /// Finds the key \p key with \p pred predicate for comparing
716 The function is an analog of \ref cds_intrusive_SplitListSet_hp_find_func "find(Q&, Func)"
717 but \p cmp is used for key compare.
718 \p Less has the interface like \p std::less.
719 \p cmp must imply the same element order as the comparator used for building the set.
721 template <typename Q, typename Less, typename Func>
722 bool find_with( Q& key, Less pred, Func f )
725 return find_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>(), f );
728 template <typename Q, typename Less, typename Func>
729 bool find_with( Q const& key, Less pred, Func f )
732 return find_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>(), f );
736 /// Checks whether the set contains \p key
738 The function searches the item with key equal to \p key
739 and returns \p true if it is found, and \p false otherwise.
741 Note the hash functor specified for class \p Traits template parameter
742 should accept a parameter of type \p Q that can be not the same as \p value_type.
743 Otherwise, you may use \p contains( Q const&, Less pred ) functions with explicit predicate for key comparing.
745 template <typename Q>
746 bool contains( Q const& key )
748 return find_( key, key_comparator());
751 template <typename Q>
752 CDS_DEPRECATED("deprecated, use contains()")
753 bool find( Q const& key )
755 return contains( key );
759 /// Checks whether the set contains \p key using \p pred predicate for searching
761 The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
762 \p Less functor has the interface like \p std::less.
763 \p Less must imply the same element order as the comparator used for building the set.
765 template <typename Q, typename Less>
766 bool contains( Q const& key, Less pred )
769 return find_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>());
772 template <typename Q, typename Less>
773 CDS_DEPRECATED("deprecated, use contains()")
774 bool find_with( Q const& key, Less pred )
776 return contains( key, pred );
780 /// Finds the key \p key and return the item found
781 /** \anchor cds_intrusive_SplitListSet_hp_get
782 The function searches the item with key equal to \p key
783 and returns the item found as \p guarded_ptr.
784 If \p key is not found the function returns an empty guarded pointer.
786 The \p disposer specified in \p OrderedList class' template parameter is called
787 by garbage collector \p GC automatically when returned \p guarded_ptr object
788 will be destroyed or released.
789 @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
793 typedef cds::intrusive::SplitListSet< your_template_params > splitlist_set;
794 splitlist_set theSet;
797 splitlist_set::guarded_ptr gp = theSet.get( 5 );
802 // Destructor of guarded_ptr releases internal HP guard
806 Note the compare functor specified for \p OrderedList template parameter
807 should accept a parameter of type \p Q that can be not the same as \p value_type.
809 template <typename Q>
810 guarded_ptr get( Q const& key )
815 /// Finds the key \p key and return the item found
817 The function is an analog of \ref cds_intrusive_SplitListSet_hp_get "get( Q const&)"
818 but \p pred is used for comparing the keys.
820 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
822 \p pred must imply the same element order as the comparator used for building the set.
824 template <typename Q, typename Less>
825 guarded_ptr get_with( Q const& key, Less pred )
827 return get_with_( key, pred );
830 /// Returns item count in the set
833 return m_ItemCounter;
836 /// Checks if the set is empty
838 Emptiness is checked by item counting: if item count is zero then the set is empty.
839 Thus, the correct item counting feature is an important part of split-list set implementation.
846 /// Clears the set (non-atomic)
848 The function unlink all items from the set.
849 The function is not atomic. After call the split-list can be non-empty.
851 For each item the \p disposer is called after unlinking.
855 iterator it = begin();
856 while ( it != end()) {
864 /// Returns internal statistics
865 stat const& statistics() const
872 template <bool IsConst>
874 :public split_list::details::iterator_type<node_traits, ordered_list, IsConst>
876 typedef split_list::details::iterator_type<node_traits, ordered_list, IsConst> iterator_base_class;
877 typedef typename iterator_base_class::list_iterator list_iterator;
880 : iterator_base_class()
883 iterator_type( iterator_type const& src )
884 : iterator_base_class( src )
887 // This ctor should be protected...
888 iterator_type( list_iterator itCur, list_iterator itEnd )
889 : iterator_base_class( itCur, itEnd )
894 ///@name Forward iterators (only for debugging purpose)
898 The forward iterator for a split-list has some features:
899 - it has no post-increment operator
900 - it depends on iterator of underlying \p OrderedList
901 - The iterator cannot be moved across thread boundary since it may contain GC's guard that is thread-private GC data.
902 - Iterator ensures thread-safety even if you delete the item that iterator points to. However, in case of concurrent
903 deleting operations it is no guarantee that you iterate all item in the set.
904 Moreover, a crash is possible when you try to iterate the next element that has been deleted by concurrent thread.
906 @warning Use this iterator on the concurrent container for debugging purpose only.
908 typedef iterator_type<false> iterator;
910 /// Const forward iterator
912 For iterator's features and requirements see \ref iterator
914 typedef iterator_type<true> const_iterator;
916 /// Returns a forward iterator addressing the first element in a split-list
918 For empty list \code begin() == end() \endcode
922 return iterator( m_List.begin(), m_List.end());
925 /// Returns an iterator that addresses the location succeeding the last element in a split-list
927 Do not use the value returned by <tt>end</tt> function to access any item.
929 The returned value can be used only to control reaching the end of the split-list.
930 For empty list \code begin() == end() \endcode
934 return iterator( m_List.end(), m_List.end());
937 /// Returns a forward const iterator addressing the first element in a split-list
938 const_iterator begin() const
942 /// Returns a forward const iterator addressing the first element in a split-list
943 const_iterator cbegin() const
945 return const_iterator( m_List.cbegin(), m_List.cend());
948 /// Returns an const iterator that addresses the location succeeding the last element in a split-list
949 const_iterator end() const
953 /// Returns an const iterator that addresses the location succeeding the last element in a split-list
954 const_iterator cend() const
956 return const_iterator( m_List.cend(), m_List.cend());
962 aux_node_type * alloc_aux_node( size_t nHash )
964 m_Stat.onHeadNodeAllocated();
965 aux_node_type* p = m_Buckets.alloc_aux_node();
971 void free_aux_node( aux_node_type * p )
973 m_Buckets.free_aux_node( p );
974 m_Stat.onHeadNodeFreed();
977 /// Calculates hash value of \p key
978 template <typename Q>
979 size_t hash_value( Q const& key ) const
981 return m_HashFunctor( key );
984 size_t bucket_no( size_t nHash ) const
986 return nHash & ((1 << m_nBucketCountLog2.load( memory_model::memory_order_relaxed )) - 1);
989 static size_t parent_bucket( size_t nBucket )
991 assert( nBucket > 0 );
992 return nBucket & ~(1 << bitop::MSBnz( nBucket ));
995 aux_node_type * init_bucket( size_t nBucket )
997 assert( nBucket > 0 );
998 size_t nParent = parent_bucket( nBucket );
1000 aux_node_type * pParentBucket = m_Buckets.bucket( nParent );
1001 if ( pParentBucket == nullptr ) {
1002 pParentBucket = init_bucket( nParent );
1003 m_Stat.onRecursiveInitBucket();
1006 assert( pParentBucket != nullptr );
1008 // Allocate a dummy node for new bucket
1009 aux_node_type * pBucket;
1010 if ( ( pBucket = m_Buckets.bucket( nBucket )) == nullptr ) {
1011 pBucket = alloc_aux_node( split_list::dummy_hash( nBucket ) );
1013 if ( m_List.insert_aux_node( pParentBucket, pBucket ) ) {
1014 m_Buckets.bucket( nBucket, pBucket );
1015 m_Stat.onNewBucket();
1019 // Another thread set the bucket. Wait while it done
1020 free_aux_node( pBucket );
1024 // There are no free buckets. It means that the bucket table is full
1025 // Wait while another thread set th bucket
1026 m_Stat.onBucketsExhausted();
1032 // Another thread set the bucket. Wait while it done
1034 // In this point, we must wait while nBucket is empty.
1035 // The compiler can decide that waiting loop can be "optimized" (stripped)
1036 // To prevent this situation, we use waiting on volatile bucket_head_ptr pointer.
1038 m_Stat.onBucketInitContenton();
1041 aux_node_type volatile * p = m_Buckets.bucket( nBucket );
1043 return const_cast<aux_node_type *>(p);
1045 m_Stat.onBusyWaitBucketInit();
1049 aux_node_type * get_bucket( size_t nHash )
1051 size_t nBucket = bucket_no( nHash );
1053 aux_node_type * pHead = m_Buckets.bucket( nBucket );
1054 if ( pHead == nullptr )
1055 pHead = init_bucket( nBucket );
1057 assert( pHead->is_dummy() );
1064 // GC and OrderedList::gc must be the same
1065 static_assert(std::is_same<gc, typename ordered_list::gc>::value, "GC and OrderedList::gc must be the same");
1067 // atomicity::empty_item_counter is not allowed as a item counter
1068 static_assert(!std::is_same<item_counter, cds::atomicity::empty_item_counter>::value,
1069 "cds::atomicity::empty_item_counter is not allowed as a item counter");
1071 // Initialize bucket 0
1072 aux_node_type * pNode = alloc_aux_node( 0 /*split_list::dummy_hash(0)*/ );
1073 assert( pNode != nullptr );
1075 // insert_aux_node cannot return false for empty list
1076 CDS_VERIFY( m_List.insert_aux_node( pNode ) );
1078 m_Buckets.bucket( 0, pNode );
1081 static size_t max_item_count( size_t nBucketCount, size_t nLoadFactor )
1083 return nBucketCount * nLoadFactor;
1086 void inc_item_count()
1088 size_t nMaxCount = m_nMaxItemCount.load( memory_model::memory_order_relaxed );
1089 if ( ++m_ItemCounter <= nMaxCount )
1092 size_t sz = m_nBucketCountLog2.load( memory_model::memory_order_relaxed );
1093 const size_t nBucketCount = static_cast<size_t>(1) << sz;
1094 if ( nBucketCount < m_Buckets.capacity() ) {
1095 // we may grow the bucket table
1096 const size_t nLoadFactor = m_Buckets.load_factor();
1097 if ( nMaxCount < max_item_count( nBucketCount, nLoadFactor ) )
1098 return; // someone already have updated m_nBucketCountLog2, so stop here
1100 m_nMaxItemCount.compare_exchange_strong( nMaxCount, max_item_count( nBucketCount << 1, nLoadFactor ),
1101 memory_model::memory_order_relaxed, atomics::memory_order_relaxed );
1102 m_nBucketCountLog2.compare_exchange_strong( sz, sz + 1, memory_model::memory_order_relaxed, atomics::memory_order_relaxed );
1105 m_nMaxItemCount.store( std::numeric_limits<size_t>::max(), memory_model::memory_order_relaxed );
1108 template <typename Q, typename Compare, typename Func>
1109 bool find_( Q& val, Compare cmp, Func f )
1111 size_t nHash = hash_value( val );
1112 split_list::details::search_value_type<Q> sv( val, split_list::regular_hash( nHash ) );
1113 aux_node_type * pHead = get_bucket( nHash );
1114 assert( pHead != nullptr );
1116 return m_Stat.onFind(
1117 m_List.find_at( pHead, sv, cmp,
1118 [&f]( value_type& item, split_list::details::search_value_type<Q>& val ) { f( item, val.val ); } )
1122 template <typename Q, typename Compare>
1123 bool find_( Q const& val, Compare cmp )
1125 size_t nHash = hash_value( val );
1126 split_list::details::search_value_type<Q const> sv( val, split_list::regular_hash( nHash ) );
1127 aux_node_type * pHead = get_bucket( nHash );
1128 assert( pHead != nullptr );
1130 return m_Stat.onFind( m_List.find_at( pHead, sv, cmp ) );
1133 template <typename Q, typename Compare>
1134 guarded_ptr get_( Q const& val, Compare cmp )
1136 size_t nHash = hash_value( val );
1137 split_list::details::search_value_type<Q const> sv( val, split_list::regular_hash( nHash ) );
1138 aux_node_type * pHead = get_bucket( nHash );
1139 assert( pHead != nullptr );
1141 guarded_ptr gp = m_List.get_at( pHead, sv, cmp );
1142 m_Stat.onFind( !gp.empty() );
1146 template <typename Q>
1147 guarded_ptr get_( Q const& key )
1149 return get_( key, key_comparator() );
1152 template <typename Q, typename Less>
1153 guarded_ptr get_with_( Q const& key, Less )
1155 return get_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>() );
1158 template <typename Q, typename Compare, typename Func>
1159 bool erase_( Q const& val, Compare cmp, Func f )
1161 size_t nHash = hash_value( val );
1162 split_list::details::search_value_type<Q const> sv( val, split_list::regular_hash( nHash ) );
1163 aux_node_type * pHead = get_bucket( nHash );
1164 assert( pHead != nullptr );
1166 if ( m_List.erase_at( pHead, sv, cmp, f ) ) {
1168 m_Stat.onEraseSuccess();
1171 m_Stat.onEraseFailed();
1175 template <typename Q, typename Compare>
1176 bool erase_( Q const& val, Compare cmp )
1178 size_t nHash = hash_value( val );
1179 split_list::details::search_value_type<Q const> sv( val, split_list::regular_hash( nHash ) );
1180 aux_node_type * pHead = get_bucket( nHash );
1181 assert( pHead != nullptr );
1183 if ( m_List.erase_at( pHead, sv, cmp ) ) {
1185 m_Stat.onEraseSuccess();
1188 m_Stat.onEraseFailed();
1192 template <typename Q, typename Compare>
1193 guarded_ptr extract_( Q const& val, Compare cmp )
1195 size_t nHash = hash_value( val );
1196 split_list::details::search_value_type<Q const> sv( val, split_list::regular_hash( nHash ) );
1197 aux_node_type * pHead = get_bucket( nHash );
1198 assert( pHead != nullptr );
1200 guarded_ptr gp = m_List.extract_at( pHead, sv, cmp );
1203 m_Stat.onExtractSuccess();
1206 m_Stat.onExtractFailed();
1210 template <typename Q>
1211 guarded_ptr extract_( Q const& key )
1213 return extract_( key, key_comparator() );
1216 template <typename Q, typename Less>
1217 guarded_ptr extract_with_( Q const& key, Less )
1219 return extract_( key, typename wrapped_ordered_list::template make_compare_from_less<Less>() );
1225 static unsigned const c_padding = cds::opt::actual_padding< traits::padding >::value;
1227 typedef typename cds::details::type_padding< bucket_table, c_padding >::type padded_bucket_table;
1228 padded_bucket_table m_Buckets; ///< bucket table
1230 typedef typename cds::details::type_padding< ordered_list_wrapper, c_padding >::type padded_ordered_list;
1231 padded_ordered_list m_List; ///< Ordered list containing split-list items
1233 atomics::atomic<size_t> m_nBucketCountLog2; ///< log2( current bucket count )
1234 atomics::atomic<size_t> m_nMaxItemCount; ///< number of items container can hold, before we have to resize
1235 item_counter m_ItemCounter; ///< Item counter
1236 hash m_HashFunctor; ///< Hash functor
1237 stat m_Stat; ///< Internal statistics
1241 }} // namespace cds::intrusive
1243 #endif // #ifndef CDSLIB_INTRUSIVE_SPLIT_LIST_H