59082192261ebc82cafb5bd03e44b8f7d3f55354
[libcds.git] / cds / container / impl / skip_list_set.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H
4 #define __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H
5
6 #include <cds/details/binary_functor_wrapper.h>
7 #include <cds/gc/guarded_ptr.h>
8 #include <cds/container/details/guarded_ptr_cast.h>
9
10 namespace cds { namespace container {
11
12     /// Lock-free skip-list set
13     /** @ingroup cds_nonintrusive_set
14         \anchor cds_nonintrusive_SkipListSet_hp
15
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
20
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
30         have this property).
31
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"
35
36         Template arguments:
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.
42
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.
47
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"
53
54         <b>Iterators</b>
55
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.
61
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
66
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
69         guards is unlimited).
70
71         The iterator class supports the following minimalistic interface:
72         \code
73         struct iterator {
74             // Default ctor
75             iterator();
76
77             // Copy ctor
78             iterator( iterator const& s);
79
80             value_type * operator ->() const;
81             value_type& operator *() const;
82
83             // Pre-increment
84             iterator& operator ++();
85
86             // Copy assignment
87             iterator& operator = (const iterator& src);
88
89             bool operator ==(iterator const& i ) const;
90             bool operator !=(iterator const& i ) const;
91         };
92         \endcode
93         Note, the iterator object returned by \p end(), \p cend() member functions points to \p nullptr and should not be dereferenced.
94     */
95     template <
96         typename GC,
97         typename T,
98 #ifdef CDS_DOXYGEN_INVOKED
99         typename Traits = skip_list::traits
100 #else
101         typename Traits
102 #endif
103     >
104     class SkipListSet:
105 #ifdef CDS_DOXYGEN_INVOKED
106         protected intrusive::SkipListSet< GC, T, Traits >
107 #else
108         protected details::make_skip_list_set< GC, T, Traits >::type
109 #endif
110     {
111         //@cond
112         typedef details::make_skip_list_set< GC, T, Traits > maker;
113         typedef typename maker::type base_class;
114         //@endcond
115     public:
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
119
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
127
128     protected:
129         //@cond
130         typedef typename maker::node_type           node_type;
131         typedef typename maker::node_allocator      node_allocator;
132
133         typedef std::unique_ptr< node_type, typename maker::node_deallocator >    scoped_node_ptr;
134         //@endcond
135
136     public:
137         /// Guarded pointer
138         typedef cds::gc::guarded_ptr< gc, node_type, value_type, details::guarded_ptr_cast_set<node_type, value_type> > guarded_ptr;
139
140     protected:
141         //@cond
142         unsigned int random_level()
143         {
144             return base_class::random_level();
145         }
146         //@endcond
147
148     public:
149         /// Default ctor
150         SkipListSet()
151             : base_class()
152         {}
153
154         /// Destructor destroys the set object
155         ~SkipListSet()
156         {}
157
158     public:
159         /// Iterator type
160         typedef skip_list::details::iterator< typename base_class::iterator >  iterator;
161
162         /// Const iterator type
163         typedef skip_list::details::iterator< typename base_class::const_iterator >   const_iterator;
164
165         /// Returns a forward iterator addressing the first element in a set
166         iterator begin()
167         {
168             return iterator( base_class::begin() );
169         }
170
171         /// Returns a forward const iterator addressing the first element in a set
172         const_iterator begin() const
173         {
174             return const_iterator( base_class::begin() );
175         }
176
177         /// Returns a forward const iterator addressing the first element in a set
178         const_iterator cbegin() const
179         {
180             return const_iterator( base_class::cbegin() );
181         }
182
183         /// Returns a forward iterator that addresses the location succeeding the last element in a set.
184         iterator end()
185         {
186             return iterator( base_class::end() );
187         }
188
189         /// Returns a forward const iterator that addresses the location succeeding the last element in a set.
190         const_iterator end() const
191         {
192             return const_iterator( base_class::end() );
193         }
194
195         /// Returns a forward const iterator that addresses the location succeeding the last element in a set.
196         const_iterator cend() const
197         {
198             return const_iterator( base_class::cend() );
199         }
200
201     public:
202         /// Inserts new node
203         /**
204             The function creates a node with copy of \p val value
205             and then inserts the node created into the set.
206
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.
210
211             Returns \p true if \p val is inserted into the set, \p false otherwise.
212         */
213         template <typename Q>
214         bool insert( Q const& val )
215         {
216             scoped_node_ptr sp( node_allocator().New( random_level(), val ));
217             if ( base_class::insert( *sp.get() )) {
218                 sp.release();
219                 return true;
220             }
221             return false;
222         }
223
224         /// Inserts new node
225         /**
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.
230
231             The functor signature is:
232             \code
233                 void func( value_type& val );
234             \endcode
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.
238         */
239         template <typename Q, typename Func>
240         bool insert( Q const& val, Func f )
241         {
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 ); } )) {
244                 sp.release();
245                 return true;
246             }
247             return false;
248         }
249
250         /// Ensures that the item exists in the set
251         /**
252             The operation performs inserting or changing data with lock-free manner.
253
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:
257             \code
258                 void func( bool bNew, value_type& item, const Q& val );
259             \endcode
260             or a functor:
261             \code
262                 struct my_functor {
263                     void operator()( bool bNew, value_type& item, const Q& val );
264                 };
265             \endcode
266
267             with arguments:
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
271
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.
274
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.
278
279             @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
280         */
281         template <typename Q, typename Func>
282         std::pair<bool, bool> ensure( const Q& val, Func func )
283         {
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 )
288                 sp.release();
289             return bRes;
290         }
291
292         /// Inserts data of type \p value_type created in-place from <tt>std::forward<Args>(args)...</tt>
293         /**
294             Returns \p true if inserting successful, \p false otherwise.
295         */
296         template <typename... Args>
297         bool emplace( Args&&... args )
298         {
299             scoped_node_ptr sp( node_allocator().New( random_level(), std::forward<Args>(args)... ));
300             if ( base_class::insert( *sp.get() )) {
301                 sp.release();
302                 return true;
303             }
304             return false;
305         }
306
307         /// Delete \p key from the set
308         /** \anchor cds_nonintrusive_SkipListSet_erase_val
309
310             The set item comparator should be able to compare the type \p value_type
311             and the type \p Q.
312
313             Return \p true if key is found and deleted, \p false otherwise
314         */
315         template <typename Q>
316         bool erase( Q const& key )
317         {
318             return base_class::erase( key );
319         }
320
321         /// Deletes the item from the set using \p pred predicate for searching
322         /**
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.
327         */
328         template <typename Q, typename Less>
329         bool erase_with( Q const& key, Less pred )
330         {
331             CDS_UNUSED( pred );
332             return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >() );
333         }
334
335         /// Delete \p key from the set
336         /** \anchor cds_nonintrusive_SkipListSet_erase_func
337
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.
340
341             The functor \p Func interface:
342             \code
343             struct extractor {
344                 void operator()(value_type const& val);
345             };
346             \endcode
347
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
351             and the type \p Q.
352
353             Return \p true if key is found and deleted, \p false otherwise
354         */
355         template <typename Q, typename Func>
356         bool erase( Q const& key, Func f )
357         {
358             return base_class::erase( key, [&f]( node_type const& node) { f( node.m_Value ); } );
359         }
360
361         /// Deletes the item from the set using \p pred predicate for searching
362         /**
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.
367         */
368         template <typename Q, typename Less, typename Func>
369         bool erase_with( Q const& key, Less pred, Func f )
370         {
371             CDS_UNUSED( pred );
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 ); } );
374         }
375
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.
381
382             Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
383
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.
387
388             Usage:
389             \code
390             typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
391             skip_list theList;
392             // ...
393             {
394                 skip_list::guarded_ptr gp;
395                 if ( theList.extract( gp, 5 ) ) {
396                     // Deal with gp
397                     // ...
398                 }
399                 // Destructor of gp releases internal HP guard and frees the pointer
400             }
401             \endcode
402         */
403         template <typename Q>
404         bool extract( guarded_ptr& result, Q const& key )
405         {
406             return base_class::extract_( result.guard(), key, typename base_class::key_comparator() );
407         }
408
409         /// Extracts the item from the set with comparing functor \p pred
410         /**
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.
413
414             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
415             in any order.
416             \p pred must imply the same element order as the comparator used for building the set.
417         */
418         template <typename Q, typename Less>
419         bool extract_with( guarded_ptr& ptr, Q const& key, Less pred )
420         {
421             CDS_UNUSED( 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>() );
424         }
425
426         /// Extracts an item with minimal key from the set
427         /**
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.
430
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.
434
435             Usage:
436             \code
437             typedef cds::continer::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
438             skip_list theList;
439             // ...
440             {
441                 skip_list::guarded_ptr gp;
442                 if ( theList.extract_min( gp )) {
443                     // Deal with gp
444                     //...
445                 }
446                 // Destructor of gp releases internal HP guard and then frees the pointer
447             }
448             \endcode
449         */
450         bool extract_min( guarded_ptr& result)
451         {
452             return base_class::extract_min_( result.guard() );
453         }
454
455         /// Extracts an item with maximal key from the set
456         /**
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.
459
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.
463
464             Usage:
465             \code
466             typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
467             skip_list theList;
468             // ...
469             {
470                 skip_list::guarded_ptr gp;
471                 if ( theList.extract_max( gp )) {
472                     // Deal with gp
473                     //...
474                 }
475                 // Destructor of gp releases internal HP guard and then frees the pointer
476             }
477             \endcode
478         */
479         bool extract_max( guarded_ptr& result )
480         {
481             return base_class::extract_max_( result.guard() );
482         }
483
484         /// Find the \p key
485         /** \anchor cds_nonintrusive_SkipListSet_find_func
486
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:
489             \code
490             struct functor {
491                 void operator()( value_type& item, Q& key );
492             };
493             \endcode
494             where \p item is the item found, \p key is the <tt>find</tt> function argument.
495
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.
500
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.
503
504             The function returns \p true if \p key is found, \p false otherwise.
505         */
506         template <typename Q, typename Func>
507         bool find( Q& key, Func f )
508         {
509             return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); });
510         }
511         //@cond
512         template <typename Q, typename Func>
513         bool find( Q const& key, Func f )
514         {
515             return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
516         }
517         //@endcond
518
519         /// Finds \p key using \p pred predicate for searching
520         /**
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.
525         */
526         template <typename Q, typename Less, typename Func>
527         bool find_with( Q& key, Less pred, Func f )
528         {
529             CDS_UNUSED( pred );
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 ); } );
532         }
533         //@cond
534         template <typename Q, typename Less, typename Func>
535         bool find_with( Q const& key, Less pred, Func f )
536         {
537             CDS_UNUSED( pred );
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 ); } );
540         }
541         //@endcond
542
543         /// Find \p key
544         /** \anchor cds_nonintrusive_SkipListSet_find_val
545
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.
548
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.
551         */
552         template <typename Q>
553         bool find( Q const& key )
554         {
555             return base_class::find( key );
556         }
557
558         /// Finds \p key using \p pred predicate for searching
559         /**
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.
564         */
565         template <typename Q, typename Less>
566         bool find_with( Q const& key, Less pred )
567         {
568             CDS_UNUSED( pred );
569             return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >());
570         }
571
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.
578
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.
583
584             Usage:
585             \code
586             typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
587             skip_list theList;
588             // ...
589             {
590                 skip_list::guarded_ptr gp;
591                 if ( theList.get( gp, 5 ) ) {
592                     // Deal with gp
593                     //...
594                 }
595                 // Destructor of guarded_ptr releases internal HP guard
596             }
597             \endcode
598
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.
601         */
602         template <typename Q>
603         bool get( guarded_ptr& result, Q const& key )
604         {
605             return base_class::get_with_( result.guard(), key, typename base_class::key_comparator() );
606         }
607
608         /// Finds \p key and return the item found
609         /**
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.
612
613             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
614             in any order.
615             \p pred must imply the same element order as the comparator used for building the set.
616         */
617         template <typename Q, typename Less>
618         bool get_with( guarded_ptr& result, Q const& key, Less pred )
619         {
620             CDS_UNUSED( 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 >());
623         }
624
625         /// Clears the set (not atomic).
626         /**
627             The function deletes all items from the set.
628             The function is not atomic, thus, in multi-threaded environment with parallel insertions
629             this sequence
630             \code
631             set.clear();
632             assert( set.empty() );
633             \endcode
634             the assertion could be raised.
635
636             For each item the \ref disposer provided by \p Traits template parameter will be called.
637         */
638         void clear()
639         {
640             base_class::clear();
641         }
642
643         /// Checks if the set is empty
644         bool empty() const
645         {
646             return base_class::empty();
647         }
648
649         /// Returns item count in the set
650         /**
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.
655         */
656         size_t size() const
657         {
658             return base_class::size();
659         }
660
661         /// Returns const reference to internal statistics
662         stat const& statistics() const
663         {
664             return base_class::statistics();
665         }
666     };
667
668 }} // namespace cds::container
669
670 #endif // #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H