3 #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H
4 #define __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H
6 #include <cds/details/binary_functor_wrapper.h>
7 #include <cds/gc/guarded_ptr.h>
8 #include <cds/container/details/guarded_ptr_cast.h>
10 namespace cds { namespace container {
12 /// Lock-free skip-list set
13 /** @ingroup cds_nonintrusive_set
14 \anchor cds_nonintrusive_SkipListSet_hp
16 The implementation of well-known probabilistic data structure called skip-list
17 invented by W.Pugh in his papers:
18 - [1989] W.Pugh Skip Lists: A Probabilistic Alternative to Balanced Trees
19 - [1990] W.Pugh A Skip List Cookbook
21 A skip-list is a probabilistic data structure that provides expected logarithmic
22 time search without the need of rebalance. The skip-list is a collection of sorted
23 linked list. Nodes are ordered by key. Each node is linked into a subset of the lists.
24 Each list has a level, ranging from 0 to 32. The bottom-level list contains
25 all the nodes, and each higher-level list is a sublist of the lower-level lists.
26 Each node is created with a random top level (with a random height), and belongs
27 to all lists up to that level. The probability that a node has the height 1 is 1/2.
28 The probability that a node has the height N is 1/2 ** N (more precisely,
29 the distribution depends on an random generator provided, but our generators
32 The lock-free variant of skip-list is implemented according to book
33 - [2008] M.Herlihy, N.Shavit "The Art of Multiprocessor Programming",
34 chapter 14.4 "A Lock-Free Concurrent Skiplist"
37 - \p GC - Garbage collector used.
38 - \p T - type to be stored in the list.
39 - \p Traits - set traits, default is \p skip_list::traits.
40 It is possible to declare option-based list with \p cds::container::skip_list::make_traits metafunction
41 istead of \p Traits template argument.
43 @warning The skip-list requires up to 67 hazard pointers that may be critical for some GCs for which
44 the guard count is limited (like as \p gc::HP). Those GCs should be explicitly initialized with
45 hazard pointer enough: \code cds::gc::HP myhp( 67 ) \endcode. Otherwise an run-time exception may be raised
46 when you try to create skip-list object.
48 @note There are several specializations of \p %SkipListSet for each \p GC. You should include:
49 - <tt><cds/container/skip_list_set_hp.h></tt> for \p gc::HP garbage collector
50 - <tt><cds/container/skip_list_set_dhp.h></tt> for \p gc::DHP garbage collector
51 - <tt><cds/container/skip_list_set_rcu.h></tt> for \ref cds_nonintrusive_SkipListSet_rcu "RCU type"
52 - <tt><cds/container/skip_list_set_nogc.h></tt> for \ref cds_nonintrusive_SkipListSet_nogc "non-deletable SkipListSet"
56 The class supports a forward iterator (\ref iterator and \ref const_iterator).
57 The iteration is ordered.
58 The iterator object is thread-safe: the element pointed by the iterator object is guarded,
59 so, the element cannot be reclaimed while the iterator object is alive.
60 However, passing an iterator object between threads is dangerous.
62 \warning Due to concurrent nature of skip-list set it is not guarantee that you can iterate
63 all elements in the set: any concurrent deletion can exclude the element
64 pointed by the iterator from the set, and your iteration can be terminated
65 before end of the set. Therefore, such iteration is more suitable for debugging purpose only
67 Remember, each iterator object requires 2 additional hazard pointers, that may be
68 a limited resource for \p GC like \p gc::HP (for \p gc::DHP the count of
71 The iterator class supports the following minimalistic interface:
78 iterator( iterator const& s);
80 value_type * operator ->() const;
81 value_type& operator *() const;
84 iterator& operator ++();
87 iterator& operator = (const iterator& src);
89 bool operator ==(iterator const& i ) const;
90 bool operator !=(iterator const& i ) const;
93 Note, the iterator object returned by \p end(), \p cend() member functions points to \p nullptr and should not be dereferenced.
98 #ifdef CDS_DOXYGEN_INVOKED
99 typename Traits = skip_list::traits
105 #ifdef CDS_DOXYGEN_INVOKED
106 protected intrusive::SkipListSet< GC, T, Traits >
108 protected details::make_skip_list_set< GC, T, Traits >::type
112 typedef details::make_skip_list_set< GC, T, Traits > maker;
113 typedef typename maker::type base_class;
116 typedef GC gc; ///< Garbage collector used
117 typedef T value_type; ///< @anchor cds_containewr_SkipListSet_value_type Value type to be stored in the set
118 typedef Traits traits; ///< Options specified
120 typedef typename base_class::back_off back_off; ///< Back-off strategy
121 typedef typename traits::allocator allocator_type; ///< Allocator type used for allocate/deallocate the skip-list nodes
122 typedef typename base_class::item_counter item_counter; ///< Item counting policy used
123 typedef typename maker::key_comparator key_comparator; ///< key comparison functor
124 typedef typename base_class::memory_model memory_model; ///< Memory ordering. See cds::opt::memory_model option
125 typedef typename traits::random_level_generator random_level_generator; ///< random level generator
126 typedef typename traits::stat stat; ///< internal statistics type
130 typedef typename maker::node_type node_type;
131 typedef typename maker::node_allocator node_allocator;
133 typedef std::unique_ptr< node_type, typename maker::node_deallocator > scoped_node_ptr;
138 typedef cds::gc::guarded_ptr< gc, node_type, value_type, details::guarded_ptr_cast_set<node_type, value_type> > guarded_ptr;
142 unsigned int random_level()
144 return base_class::random_level();
154 /// Destructor destroys the set object
160 typedef skip_list::details::iterator< typename base_class::iterator > iterator;
162 /// Const iterator type
163 typedef skip_list::details::iterator< typename base_class::const_iterator > const_iterator;
165 /// Returns a forward iterator addressing the first element in a set
168 return iterator( base_class::begin() );
171 /// Returns a forward const iterator addressing the first element in a set
172 const_iterator begin() const
174 return const_iterator( base_class::begin() );
177 /// Returns a forward const iterator addressing the first element in a set
178 const_iterator cbegin() const
180 return const_iterator( base_class::cbegin() );
183 /// Returns a forward iterator that addresses the location succeeding the last element in a set.
186 return iterator( base_class::end() );
189 /// Returns a forward const iterator that addresses the location succeeding the last element in a set.
190 const_iterator end() const
192 return const_iterator( base_class::end() );
195 /// Returns a forward const iterator that addresses the location succeeding the last element in a set.
196 const_iterator cend() const
198 return const_iterator( base_class::cend() );
204 The function creates a node with copy of \p val value
205 and then inserts the node created into the set.
207 The type \p Q should contain as minimum the complete key for the node.
208 The object of \ref value_type should be constructible from a value of type \p Q.
209 In trivial case, \p Q is equal to \ref value_type.
211 Returns \p true if \p val is inserted into the set, \p false otherwise.
213 template <typename Q>
214 bool insert( Q const& val )
216 scoped_node_ptr sp( node_allocator().New( random_level(), val ));
217 if ( base_class::insert( *sp.get() )) {
226 The function allows to split creating of new item into two part:
227 - create item with key only
228 - insert new item into the set
229 - if inserting is success, calls \p f functor to initialize value-fields of \p val.
231 The functor signature is:
233 void func( value_type& val );
235 where \p val is the item inserted. User-defined functor \p f should guarantee that during changing
236 \p val no any other changes could be made on this set's item by concurrent threads.
237 The user-defined functor is called only if the inserting is success.
239 template <typename Q, typename Func>
240 bool insert( Q const& val, Func f )
242 scoped_node_ptr sp( node_allocator().New( random_level(), val ));
243 if ( base_class::insert( *sp.get(), [&f]( node_type& val ) { f( val.m_Value ); } )) {
250 /// Ensures that the item exists in the set
252 The operation performs inserting or changing data with lock-free manner.
254 If the \p val key not found in the set, then the new item created from \p val
255 is inserted into the set. Otherwise, the functor \p func is called with the item found.
256 The functor \p Func should be a function with signature:
258 void func( bool bNew, value_type& item, const Q& val );
263 void operator()( bool bNew, value_type& item, const Q& val );
268 - \p bNew - \p true if the item has been inserted, \p false otherwise
269 - \p item - item of the set
270 - \p val - argument \p key passed into the \p %ensure() function
272 The functor may change non-key fields of the \p item; however, \p func must guarantee
273 that during changing no any other modifications could be made on this item by concurrent threads.
275 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
276 \p second is true if new item has been added or \p false if the item with \p key
277 already is in the set.
279 @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
281 template <typename Q, typename Func>
282 std::pair<bool, bool> ensure( const Q& val, Func func )
284 scoped_node_ptr sp( node_allocator().New( random_level(), val ));
285 std::pair<bool, bool> bRes = base_class::ensure( *sp,
286 [&func, &val](bool bNew, node_type& node, node_type&){ func( bNew, node.m_Value, val ); });
287 if ( bRes.first && bRes.second )
292 /// Inserts data of type \p value_type created in-place from <tt>std::forward<Args>(args)...</tt>
294 Returns \p true if inserting successful, \p false otherwise.
296 template <typename... Args>
297 bool emplace( Args&&... args )
299 scoped_node_ptr sp( node_allocator().New( random_level(), std::forward<Args>(args)... ));
300 if ( base_class::insert( *sp.get() )) {
307 /// Delete \p key from the set
308 /** \anchor cds_nonintrusive_SkipListSet_erase_val
310 The set item comparator should be able to compare the type \p value_type
313 Return \p true if key is found and deleted, \p false otherwise
315 template <typename Q>
316 bool erase( Q const& key )
318 return base_class::erase( key );
321 /// Deletes the item from the set using \p pred predicate for searching
323 The function is an analog of \ref cds_nonintrusive_SkipListSet_erase_val "erase(Q const&)"
324 but \p pred is used for key comparing.
325 \p Less functor has the interface like \p std::less.
326 \p Less must imply the same element order as the comparator used for building the set.
328 template <typename Q, typename Less>
329 bool erase_with( Q const& key, Less pred )
332 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >() );
335 /// Delete \p key from the set
336 /** \anchor cds_nonintrusive_SkipListSet_erase_func
338 The function searches an item with key \p key, calls \p f functor
339 and deletes the item. If \p key is not found, the functor is not called.
341 The functor \p Func interface:
344 void operator()(value_type const& val);
348 Since the key of \p value_type is not explicitly specified,
349 template parameter \p Q defines the key type to search in the list.
350 The list item comparator should be able to compare the type \p T of list item
353 Return \p true if key is found and deleted, \p false otherwise
355 template <typename Q, typename Func>
356 bool erase( Q const& key, Func f )
358 return base_class::erase( key, [&f]( node_type const& node) { f( node.m_Value ); } );
361 /// Deletes the item from the set using \p pred predicate for searching
363 The function is an analog of \ref cds_nonintrusive_SkipListSet_erase_func "erase(Q const&, Func)"
364 but \p pred is used for key comparing.
365 \p Less functor has the interface like \p std::less.
366 \p Less must imply the same element order as the comparator used for building the set.
368 template <typename Q, typename Less, typename Func>
369 bool erase_with( Q const& key, Less pred, Func f )
372 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
373 [&f]( node_type const& node) { f( node.m_Value ); } );
376 /// Extracts the item from the set with specified \p key
377 /** \anchor cds_nonintrusive_SkipListSet_hp_extract
378 The function searches an item with key equal to \p key in the set,
379 unlinks it from the set, and returns it in \p result parameter.
380 If the item with key equal to \p key is not found the function returns \p false.
382 Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
384 The item extracted is freed automatically by garbage collector \p GC
385 when returned \ref guarded_ptr object will be destroyed or released.
386 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
390 typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
394 skip_list::guarded_ptr gp;
395 if ( theList.extract( gp, 5 ) ) {
399 // Destructor of gp releases internal HP guard and frees the pointer
403 template <typename Q>
404 bool extract( guarded_ptr& result, Q const& key )
406 return base_class::extract_( result.guard(), key, typename base_class::key_comparator() );
409 /// Extracts the item from the set with comparing functor \p pred
411 The function is an analog of \ref cds_nonintrusive_SkipListSet_hp_extract "extract(Q const&)"
412 but \p pred predicate is used for key comparing.
414 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
416 \p pred must imply the same element order as the comparator used for building the set.
418 template <typename Q, typename Less>
419 bool extract_with( guarded_ptr& ptr, Q const& key, Less pred )
422 typedef cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor > wrapped_less;
423 return base_class::extract_( ptr.guard(), key, cds::opt::details::make_comparator_from_less<wrapped_less>() );
426 /// Extracts an item with minimal key from the set
428 The function searches an item with minimal key, unlinks it, and returns the item found in \p result parameter.
429 If the skip-list is empty the function returns \p false.
431 The item extracted is freed automatically by garbage collector \p GC
432 when returned \ref guarded_ptr object will be destroyed or released.
433 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
437 typedef cds::continer::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
441 skip_list::guarded_ptr gp;
442 if ( theList.extract_min( gp )) {
446 // Destructor of gp releases internal HP guard and then frees the pointer
450 bool extract_min( guarded_ptr& result)
452 return base_class::extract_min_( result.guard() );
455 /// Extracts an item with maximal key from the set
457 The function searches an item with maximal key, unlinks it, and returns the pointer to item found in \p result parameter.
458 If the skip-list is empty the function returns \p false.
460 The item found is freed by garbage collector \p GC automatically
461 when returned \ref guarded_ptr object will be destroyed or released.
462 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
466 typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
470 skip_list::guarded_ptr gp;
471 if ( theList.extract_max( gp )) {
475 // Destructor of gp releases internal HP guard and then frees the pointer
479 bool extract_max( guarded_ptr& result )
481 return base_class::extract_max_( result.guard() );
485 /** \anchor cds_nonintrusive_SkipListSet_find_func
487 The function searches the item with key equal to \p key and calls the functor \p f for item found.
488 The interface of \p Func functor is:
491 void operator()( value_type& item, Q& key );
494 where \p item is the item found, \p key is the <tt>find</tt> function argument.
496 The functor may change non-key fields of \p item. Note that the functor is only guarantee
497 that \p item cannot be disposed during functor is executing.
498 The functor does not serialize simultaneous access to the set's \p item. If such access is
499 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
501 Note the hash functor specified for class \p Traits template parameter
502 should accept a parameter of type \p Q that may be not the same as \p value_type.
504 The function returns \p true if \p key is found, \p false otherwise.
506 template <typename Q, typename Func>
507 bool find( Q& key, Func f )
509 return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); });
512 template <typename Q, typename Func>
513 bool find( Q const& key, Func f )
515 return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
519 /// Finds \p key using \p pred predicate for searching
521 The function is an analog of \ref cds_nonintrusive_SkipListSet_find_func "find(Q&, Func)"
522 but \p pred is used for key comparing.
523 \p Less functor has the interface like \p std::less.
524 \p Less must imply the same element order as the comparator used for building the set.
526 template <typename Q, typename Less, typename Func>
527 bool find_with( Q& key, Less pred, Func f )
530 return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
531 [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
534 template <typename Q, typename Less, typename Func>
535 bool find_with( Q const& key, Less pred, Func f )
538 return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
539 [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
544 /** \anchor cds_nonintrusive_SkipListSet_find_val
546 The function searches the item with key equal to \p key
547 and returns \p true if it is found, and \p false otherwise.
549 Note the hash functor specified for class \p Traits template parameter
550 should accept a parameter of type \p Q that may be not the same as \ref value_type.
552 template <typename Q>
553 bool find( Q const& key )
555 return base_class::find( key );
558 /// Finds \p key using \p pred predicate for searching
560 The function is an analog of \ref cds_nonintrusive_SkipListSet_find_val "find(Q const&)"
561 but \p pred is used for key comparing.
562 \p Less functor has the interface like \p std::less.
563 \p Less must imply the same element order as the comparator used for building the set.
565 template <typename Q, typename Less>
566 bool find_with( Q const& key, Less pred )
569 return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >());
572 /// Finds \p key and return the item found
573 /** \anchor cds_nonintrusive_SkipListSet_hp_get
574 The function searches the item with key equal to \p key
575 and assigns the item found to guarded pointer \p result.
576 The function returns \p true if \p key is found, and \p false otherwise.
577 If \p key is not found the \p result parameter is left unchanged.
579 It is safe when a concurrent thread erases the item returned in \p result guarded pointer.
580 In this case the item will be freed later by garbage collector \p GC automatically
581 when \p guarded_ptr object will be destroyed or released.
582 @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
586 typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
590 skip_list::guarded_ptr gp;
591 if ( theList.get( gp, 5 ) ) {
595 // Destructor of guarded_ptr releases internal HP guard
599 Note the compare functor specified for class \p Traits template parameter
600 should accept a parameter of type \p Q that can be not the same as \p value_type.
602 template <typename Q>
603 bool get( guarded_ptr& result, Q const& key )
605 return base_class::get_with_( result.guard(), key, typename base_class::key_comparator() );
608 /// Finds \p key and return the item found
610 The function is an analog of \ref cds_nonintrusive_SkipListSet_hp_get "get( guarded_ptr&, Q const&)"
611 but \p pred is used for comparing the keys.
613 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
615 \p pred must imply the same element order as the comparator used for building the set.
617 template <typename Q, typename Less>
618 bool get_with( guarded_ptr& result, Q const& key, Less pred )
621 typedef cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor > wrapped_less;
622 return base_class::get_with_( result.guard(), key, cds::opt::details::make_comparator_from_less< wrapped_less >());
625 /// Clears the set (not atomic).
627 The function deletes all items from the set.
628 The function is not atomic, thus, in multi-threaded environment with parallel insertions
632 assert( set.empty() );
634 the assertion could be raised.
636 For each item the \ref disposer provided by \p Traits template parameter will be called.
643 /// Checks if the set is empty
646 return base_class::empty();
649 /// Returns item count in the set
651 The value returned depends on item counter type provided by \p Traits template parameter.
652 If it is \p atomicity::empty_item_counter this function always returns 0.
653 Therefore, the function is not suitable for checking the set emptiness, use \p empty()
654 member function for this purpose.
658 return base_class::size();
661 /// Returns const reference to internal statistics
662 stat const& statistics() const
664 return base_class::statistics();
668 }} // namespace cds::container
670 #endif // #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H