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::PTB 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 )
331 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >() );
334 /// Delete \p key from the set
335 /** \anchor cds_nonintrusive_SkipListSet_erase_func
337 The function searches an item with key \p key, calls \p f functor
338 and deletes the item. If \p key is not found, the functor is not called.
340 The functor \p Func interface:
343 void operator()(value_type const& val);
347 Since the key of \p value_type is not explicitly specified,
348 template parameter \p Q defines the key type to search in the list.
349 The list item comparator should be able to compare the type \p T of list item
352 Return \p true if key is found and deleted, \p false otherwise
354 template <typename Q, typename Func>
355 bool erase( Q const& key, Func f )
357 return base_class::erase( key, [&f]( node_type const& node) { f( node.m_Value ); } );
360 /// Deletes the item from the set using \p pred predicate for searching
362 The function is an analog of \ref cds_nonintrusive_SkipListSet_erase_func "erase(Q const&, Func)"
363 but \p pred is used for key comparing.
364 \p Less functor has the interface like \p std::less.
365 \p Less must imply the same element order as the comparator used for building the set.
367 template <typename Q, typename Less, typename Func>
368 bool erase_with( Q const& key, Less pred, Func f )
370 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
371 [&f]( node_type const& node) { f( node.m_Value ); } );
374 /// Extracts the item from the set with specified \p key
375 /** \anchor cds_nonintrusive_SkipListSet_hp_extract
376 The function searches an item with key equal to \p key in the set,
377 unlinks it from the set, and returns it in \p result parameter.
378 If the item with key equal to \p key is not found the function returns \p false.
380 Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
382 The item extracted is freed automatically by garbage collector \p GC
383 when returned \ref guarded_ptr object will be destroyed or released.
384 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
388 typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
392 skip_list::guarded_ptr gp;
393 if ( theList.extract( gp, 5 ) ) {
397 // Destructor of gp releases internal HP guard and frees the pointer
401 template <typename Q>
402 bool extract( guarded_ptr& result, Q const& key )
404 return base_class::extract_( result.guard(), key, typename base_class::key_comparator() );
407 /// Extracts the item from the set with comparing functor \p pred
409 The function is an analog of \ref cds_nonintrusive_SkipListSet_hp_extract "extract(Q const&)"
410 but \p pred predicate is used for key comparing.
412 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
414 \p pred must imply the same element order as the comparator used for building the set.
416 template <typename Q, typename Less>
417 bool extract_with( guarded_ptr& ptr, Q const& key, Less pred )
419 typedef cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor > wrapped_less;
420 return base_class::extract_( ptr.guard(), key, cds::opt::details::make_comparator_from_less<wrapped_less>() );
423 /// Extracts an item with minimal key from the set
425 The function searches an item with minimal key, unlinks it, and returns the item found in \p result parameter.
426 If the skip-list is empty the function returns \p false.
428 The item extracted is freed automatically by garbage collector \p GC
429 when returned \ref guarded_ptr object will be destroyed or released.
430 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
434 typedef cds::continer::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
438 skip_list::guarded_ptr gp;
439 if ( theList.extract_min( gp )) {
443 // Destructor of gp releases internal HP guard and then frees the pointer
447 bool extract_min( guarded_ptr& result)
449 return base_class::extract_min_( result.guard() );
452 /// Extracts an item with maximal key from the set
454 The function searches an item with maximal key, unlinks it, and returns the pointer to item found in \p result parameter.
455 If the skip-list is empty the function returns \p false.
457 The item found is freed by garbage collector \p GC automatically
458 when returned \ref guarded_ptr object will be destroyed or released.
459 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
463 typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
467 skip_list::guarded_ptr gp;
468 if ( theList.extract_max( gp )) {
472 // Destructor of gp releases internal HP guard and then frees the pointer
476 bool extract_max( guarded_ptr& result )
478 return base_class::extract_max_( result.guard() );
482 /** \anchor cds_nonintrusive_SkipListSet_find_func
484 The function searches the item with key equal to \p key and calls the functor \p f for item found.
485 The interface of \p Func functor is:
488 void operator()( value_type& item, Q& key );
491 where \p item is the item found, \p key is the <tt>find</tt> function argument.
493 The functor may change non-key fields of \p item. Note that the functor is only guarantee
494 that \p item cannot be disposed during functor is executing.
495 The functor does not serialize simultaneous access to the set's \p item. If such access is
496 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
498 Note the hash functor specified for class \p Traits template parameter
499 should accept a parameter of type \p Q that may be not the same as \p value_type.
501 The function returns \p true if \p key is found, \p false otherwise.
503 template <typename Q, typename Func>
504 bool find( Q& key, Func f )
506 return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); });
509 /// Finds \p key using \p pred predicate for searching
511 The function is an analog of \ref cds_nonintrusive_SkipListSet_find_func "find(Q&, Func)"
512 but \p pred is used for key comparing.
513 \p Less functor has the interface like \p std::less.
514 \p Less must imply the same element order as the comparator used for building the set.
516 template <typename Q, typename Less, typename Func>
517 bool find_with( Q& key, Less pred, Func f )
519 return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
520 [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
524 /** \anchor cds_nonintrusive_SkipListSet_find_val
526 The function searches the item with key equal to \p key
527 and returns \p true if it is found, and \p false otherwise.
529 Note the hash functor specified for class \p Traits template parameter
530 should accept a parameter of type \p Q that may be not the same as \ref value_type.
532 template <typename Q>
533 bool find( Q const& key )
535 return base_class::find( key );
538 /// Finds \p key using \p pred predicate for searching
540 The function is an analog of \ref cds_nonintrusive_SkipListSet_find_val "find(Q const&)"
541 but \p pred is used for key comparing.
542 \p Less functor has the interface like \p std::less.
543 \p Less must imply the same element order as the comparator used for building the set.
545 template <typename Q, typename Less>
546 bool find_with( Q const& key, Less pred )
548 return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >());
551 /// Finds \p key and return the item found
552 /** \anchor cds_nonintrusive_SkipListSet_hp_get
553 The function searches the item with key equal to \p key
554 and assigns the item found to guarded pointer \p result.
555 The function returns \p true if \p key is found, and \p false otherwise.
556 If \p key is not found the \p result parameter is left unchanged.
558 It is safe when a concurrent thread erases the item returned in \p result guarded pointer.
559 In this case the item will be freed later by garbage collector \p GC automatically
560 when \p guarded_ptr object will be destroyed or released.
561 @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
565 typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits > skip_list;
569 skip_list::guarded_ptr gp;
570 if ( theList.get( gp, 5 ) ) {
574 // Destructor of guarded_ptr releases internal HP guard
578 Note the compare functor specified for class \p Traits template parameter
579 should accept a parameter of type \p Q that can be not the same as \p value_type.
581 template <typename Q>
582 bool get( guarded_ptr& result, Q const& key )
584 return base_class::get_with_( result.guard(), key, typename base_class::key_comparator() );
587 /// Finds \p key and return the item found
589 The function is an analog of \ref cds_nonintrusive_SkipListSet_hp_get "get( guarded_ptr&, Q const&)"
590 but \p pred is used for comparing the keys.
592 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
594 \p pred must imply the same element order as the comparator used for building the set.
596 template <typename Q, typename Less>
597 bool get_with( guarded_ptr& result, Q const& key, Less pred )
599 typedef cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor > wrapped_less;
600 return base_class::get_with_( result.guard(), key, cds::opt::details::make_comparator_from_less< wrapped_less >());
603 /// Clears the set (not atomic).
605 The function deletes all items from the set.
606 The function is not atomic, thus, in multi-threaded environment with parallel insertions
610 assert( set.empty() );
612 the assertion could be raised.
614 For each item the \ref disposer provided by \p Traits template parameter will be called.
621 /// Checks if the set is empty
624 return base_class::empty();
627 /// Returns item count in the set
629 The value returned depends on item counter type provided by \p Traits template parameter.
630 If it is \p atomicity::empty_item_counter this function always returns 0.
631 Therefore, the function is not suitable for checking the set emptiness, use \p empty()
632 member function for this purpose.
636 return base_class::size();
639 /// Returns const reference to internal statistics
640 stat const& statistics() const
642 return base_class::statistics();
646 }} // namespace cds::container
648 #endif // #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H