9de1eb5ec6c928fdaa389b7dee0189113826a4cf
[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             return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >() );
332         }
333
334         /// Delete \p key from the set
335         /** \anchor cds_nonintrusive_SkipListSet_erase_func
336
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.
339
340             The functor \p Func interface:
341             \code
342             struct extractor {
343                 void operator()(value_type const& val);
344             };
345             \endcode
346
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
350             and the type \p Q.
351
352             Return \p true if key is found and deleted, \p false otherwise
353         */
354         template <typename Q, typename Func>
355         bool erase( Q const& key, Func f )
356         {
357             return base_class::erase( key, [&f]( node_type const& node) { f( node.m_Value ); } );
358         }
359
360         /// Deletes the item from the set using \p pred predicate for searching
361         /**
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.
366         */
367         template <typename Q, typename Less, typename Func>
368         bool erase_with( Q const& key, Less pred, Func f )
369         {
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 ); } );
372         }
373
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.
379
380             Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
381
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.
385
386             Usage:
387             \code
388             typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
389             skip_list theList;
390             // ...
391             {
392                 skip_list::guarded_ptr gp;
393                 if ( theList.extract( gp, 5 ) ) {
394                     // Deal with gp
395                     // ...
396                 }
397                 // Destructor of gp releases internal HP guard and frees the pointer
398             }
399             \endcode
400         */
401         template <typename Q>
402         bool extract( guarded_ptr& result, Q const& key )
403         {
404             return base_class::extract_( result.guard(), key, typename base_class::key_comparator() );
405         }
406
407         /// Extracts the item from the set with comparing functor \p pred
408         /**
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.
411
412             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
413             in any order.
414             \p pred must imply the same element order as the comparator used for building the set.
415         */
416         template <typename Q, typename Less>
417         bool extract_with( guarded_ptr& ptr, Q const& key, Less pred )
418         {
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>() );
421         }
422
423         /// Extracts an item with minimal key from the set
424         /**
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.
427
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.
431
432             Usage:
433             \code
434             typedef cds::continer::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
435             skip_list theList;
436             // ...
437             {
438                 skip_list::guarded_ptr gp;
439                 if ( theList.extract_min( gp )) {
440                     // Deal with gp
441                     //...
442                 }
443                 // Destructor of gp releases internal HP guard and then frees the pointer
444             }
445             \endcode
446         */
447         bool extract_min( guarded_ptr& result)
448         {
449             return base_class::extract_min_( result.guard() );
450         }
451
452         /// Extracts an item with maximal key from the set
453         /**
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.
456
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.
460
461             Usage:
462             \code
463             typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
464             skip_list theList;
465             // ...
466             {
467                 skip_list::guarded_ptr gp;
468                 if ( theList.extract_max( gp )) {
469                     // Deal with gp
470                     //...
471                 }
472                 // Destructor of gp releases internal HP guard and then frees the pointer
473             }
474             \endcode
475         */
476         bool extract_max( guarded_ptr& result )
477         {
478             return base_class::extract_max_( result.guard() );
479         }
480
481         /// Find the \p key
482         /** \anchor cds_nonintrusive_SkipListSet_find_func
483
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:
486             \code
487             struct functor {
488                 void operator()( value_type& item, Q& key );
489             };
490             \endcode
491             where \p item is the item found, \p key is the <tt>find</tt> function argument.
492
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.
497
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.
500
501             The function returns \p true if \p key is found, \p false otherwise.
502         */
503         template <typename Q, typename Func>
504         bool find( Q& key, Func f )
505         {
506             return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); });
507         }
508         //@cond
509         template <typename Q, typename Func>
510         bool find( Q const& key, Func f )
511         {
512             return base_class::find( key, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
513         }
514         //@endcond
515
516         /// Finds \p key using \p pred predicate for searching
517         /**
518             The function is an analog of \ref cds_nonintrusive_SkipListSet_find_func "find(Q&, Func)"
519             but \p pred is used for key comparing.
520             \p Less functor has the interface like \p std::less.
521             \p Less must imply the same element order as the comparator used for building the set.
522         */
523         template <typename Q, typename Less, typename Func>
524         bool find_with( Q& key, Less pred, Func f )
525         {
526             return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
527                 [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
528         }
529         //@cond
530         template <typename Q, typename Less, typename Func>
531         bool find_with( Q const& key, Less pred, Func f )
532         {
533             return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
534                                           [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
535         }
536         //@endcond
537
538         /// Find \p key
539         /** \anchor cds_nonintrusive_SkipListSet_find_val
540
541             The function searches the item with key equal to \p key
542             and returns \p true if it is found, and \p false otherwise.
543
544             Note the hash functor specified for class \p Traits template parameter
545             should accept a parameter of type \p Q that may be not the same as \ref value_type.
546         */
547         template <typename Q>
548         bool find( Q const& key )
549         {
550             return base_class::find( key );
551         }
552
553         /// Finds \p key using \p pred predicate for searching
554         /**
555             The function is an analog of \ref cds_nonintrusive_SkipListSet_find_val "find(Q const&)"
556             but \p pred is used for key comparing.
557             \p Less functor has the interface like \p std::less.
558             \p Less must imply the same element order as the comparator used for building the set.
559         */
560         template <typename Q, typename Less>
561         bool find_with( Q const& key, Less pred )
562         {
563             return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >());
564         }
565
566         /// Finds \p key and return the item found
567         /** \anchor cds_nonintrusive_SkipListSet_hp_get
568             The function searches the item with key equal to \p key
569             and assigns the item found to guarded pointer \p result.
570             The function returns \p true if \p key is found, and \p false otherwise.
571             If \p key is not found the \p result parameter is left unchanged.
572
573             It is safe when a concurrent thread erases the item returned in \p result guarded pointer.
574             In this case the item will be freed later by garbage collector \p GC automatically
575             when \p guarded_ptr object will be destroyed or released.
576             @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
577
578             Usage:
579             \code
580             typedef cds::container::SkipListSet< cds::gc::HP, foo, my_traits >  skip_list;
581             skip_list theList;
582             // ...
583             {
584                 skip_list::guarded_ptr gp;
585                 if ( theList.get( gp, 5 ) ) {
586                     // Deal with gp
587                     //...
588                 }
589                 // Destructor of guarded_ptr releases internal HP guard
590             }
591             \endcode
592
593             Note the compare functor specified for class \p Traits template parameter
594             should accept a parameter of type \p Q that can be not the same as \p value_type.
595         */
596         template <typename Q>
597         bool get( guarded_ptr& result, Q const& key )
598         {
599             return base_class::get_with_( result.guard(), key, typename base_class::key_comparator() );
600         }
601
602         /// Finds \p key and return the item found
603         /**
604             The function is an analog of \ref cds_nonintrusive_SkipListSet_hp_get "get( guarded_ptr&, Q const&)"
605             but \p pred is used for comparing the keys.
606
607             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
608             in any order.
609             \p pred must imply the same element order as the comparator used for building the set.
610         */
611         template <typename Q, typename Less>
612         bool get_with( guarded_ptr& result, Q const& key, Less pred )
613         {
614             typedef cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >  wrapped_less;
615             return base_class::get_with_( result.guard(), key, cds::opt::details::make_comparator_from_less< wrapped_less >());
616         }
617
618         /// Clears the set (not atomic).
619         /**
620             The function deletes all items from the set.
621             The function is not atomic, thus, in multi-threaded environment with parallel insertions
622             this sequence
623             \code
624             set.clear();
625             assert( set.empty() );
626             \endcode
627             the assertion could be raised.
628
629             For each item the \ref disposer provided by \p Traits template parameter will be called.
630         */
631         void clear()
632         {
633             base_class::clear();
634         }
635
636         /// Checks if the set is empty
637         bool empty() const
638         {
639             return base_class::empty();
640         }
641
642         /// Returns item count in the set
643         /**
644             The value returned depends on item counter type provided by \p Traits template parameter.
645             If it is \p atomicity::empty_item_counter this function always returns 0.
646             Therefore, the function is not suitable for checking the set emptiness, use \p empty()
647             member function for this purpose.
648         */
649         size_t size() const
650         {
651             return base_class::size();
652         }
653
654         /// Returns const reference to internal statistics
655         stat const& statistics() const
656         {
657             return base_class::statistics();
658         }
659     };
660
661 }} // namespace cds::container
662
663 #endif // #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_SET_H