2 This file is a part of libcds - Concurrent Data Structures library
4 (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
6 Source code repo: http://github.com/khizmax/libcds/
7 Download: http://sourceforge.net/projects/libcds/files/
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions are met:
12 * Redistributions of source code must retain the above copyright notice, this
13 list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 this list of conditions and the following disclaimer in the documentation
17 and/or other materials provided with the distribution.
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #ifndef CDSLIB_CONTAINER_SKIP_LIST_SET_RCU_H
32 #define CDSLIB_CONTAINER_SKIP_LIST_SET_RCU_H
34 #include <cds/intrusive/skip_list_rcu.h>
35 #include <cds/container/details/make_skip_list_set.h>
37 namespace cds { namespace container {
39 /// Lock-free skip-list set (template specialization for \ref cds_urcu_desc "RCU")
40 /** @ingroup cds_nonintrusive_set
41 \anchor cds_nonintrusive_SkipListSet_rcu
43 The implementation of well-known probabilistic data structure called skip-list
44 invented by W.Pugh in his papers:
45 - [1989] W.Pugh Skip Lists: A Probabilistic Alternative to Balanced Trees
46 - [1990] W.Pugh A Skip List Cookbook
48 A skip-list is a probabilistic data structure that provides expected logarithmic
49 time search without the need of rebalance. The skip-list is a collection of sorted
50 linked list. Nodes are ordered by key. Each node is linked into a subset of the lists.
51 Each list has a level, ranging from 0 to 32. The bottom-level list contains
52 all the nodes, and each higher-level list is a sublist of the lower-level lists.
53 Each node is created with a random top level (with a random height), and belongs
54 to all lists up to that level. The probability that a node has the height 1 is 1/2.
55 The probability that a node has the height N is 1/2 ** N (more precisely,
56 the distribution depends on an random generator provided, but our generators
59 The lock-free variant of skip-list is implemented according to book
60 - [2008] M.Herlihy, N.Shavit "The Art of Multiprocessor Programming",
61 chapter 14.4 "A Lock-Free Concurrent Skiplist"
64 - \p RCU - one of \ref cds_urcu_gc "RCU type".
65 - \p T - type to be stored in the list.
66 - \p Traits - set traits, default is skip_list::traits for explanation.
68 It is possible to declare option-based list with cds::container::skip_list::make_traits metafunction istead of \p Traits template
70 Template argument list \p Options of cds::container::skip_list::make_traits metafunction are:
71 - opt::compare - key comparison functor. No default functor is provided.
72 If the option is not specified, the opt::less is used.
73 - opt::less - specifies binary predicate used for key comparison. Default is \p std::less<T>.
74 - opt::item_counter - the type of item counting feature. Default is \ref atomicity::empty_item_counter that is no item counting.
75 - opt::memory_model - C++ memory ordering model. Can be opt::v::relaxed_ordering (relaxed memory model, the default)
76 or opt::v::sequential_consistent (sequentially consisnent memory model).
77 - skip_list::random_level_generator - random level generator. Can be skip_list::xorshift, skip_list::turbo_pascal or
78 user-provided one. See skip_list::random_level_generator option description for explanation.
79 Default is \p %skip_list::turbo_pascal.
80 - opt::allocator - allocator for skip-list node. Default is \ref CDS_DEFAULT_ALLOCATOR.
81 - opt::back_off - back-off strategy used. If the option is not specified, the cds::backoff::Default is used.
82 - opt::stat - internal statistics. Available types: skip_list::stat, skip_list::empty_stat (the default)
83 - opt::rcu_check_deadlock - a deadlock checking policy. Default is opt::v::rcu_throw_deadlock
85 @note Before including <tt><cds/container/skip_list_set_rcu.h></tt> you should include appropriate RCU header file,
86 see \ref cds_urcu_gc "RCU type" for list of existing RCU class and corresponding header files.
90 The class supports a forward iterator (\ref iterator and \ref const_iterator).
91 The iteration is ordered.
93 You may iterate over skip-list set items only under RCU lock.
94 Only in this case the iterator is thread-safe since
95 while RCU is locked any set's item cannot be reclaimed.
97 The requirement of RCU lock during iterating means that deletion of the elements (i.e. \ref erase)
100 @warning The iterator object cannot be passed between threads
102 Example how to use skip-list set iterators:
104 // First, you should include the header for RCU type you have chosen
105 #include <cds/urcu/general_buffered.h>
106 #include <cds/container/skip_list_set_rcu.h>
108 typedef cds::urcu::gc< cds::urcu::general_buffered<> > rcu_type;
114 // Traits for your skip-list.
115 // At least, you should define cds::opt::less or cds::opt::compare for Foo struct
116 struct my_traits: public cds::continer::skip_list::traits
120 typedef cds::container::SkipListSet< rcu_type, Foo, my_traits > my_skiplist_set;
122 my_skiplist_set theSet;
128 // Apply RCU locking manually
129 typename rcu_type::scoped_lock sl;
131 for ( auto it = theList.begin(); it != theList.end(); ++it ) {
135 // rcu_type::scoped_lock destructor releases RCU lock implicitly
139 \warning Due to concurrent nature of skip-list set it is not guarantee that you can iterate
140 all elements in the set: any concurrent deletion can exclude the element
141 pointed by the iterator from the set, and your iteration can be terminated
142 before end of the set. Therefore, such iteration is more suitable for debugging purposes
144 The iterator class supports the following minimalistic interface:
151 iterator( iterator const& s);
153 value_type * operator ->() const;
154 value_type& operator *() const;
157 iterator& operator ++();
160 iterator& operator = (const iterator& src);
162 bool operator ==(iterator const& i ) const;
163 bool operator !=(iterator const& i ) const;
166 Note, the iterator object returned by \ref end, \p cend member functions points to \p nullptr and should not be dereferenced.
171 #ifdef CDS_DOXYGEN_INVOKED
172 typename Traits = skip_list::traits
177 class SkipListSet< cds::urcu::gc< RCU >, T, Traits >:
178 #ifdef CDS_DOXYGEN_INVOKED
179 protected intrusive::SkipListSet< cds::urcu::gc< RCU >, T, Traits >
181 protected details::make_skip_list_set< cds::urcu::gc< RCU >, T, Traits >::type
185 typedef details::make_skip_list_set< cds::urcu::gc< RCU >, T, Traits > maker;
186 typedef typename maker::type base_class;
189 typedef typename base_class::gc gc ; ///< Garbage collector used
190 typedef T value_type ; ///< Value type stored in the set
191 typedef Traits traits ; ///< Options specified
193 typedef typename base_class::back_off back_off ; ///< Back-off strategy used
194 typedef typename traits::allocator allocator_type ; ///< Allocator type used for allocate/deallocate the skip-list nodes
195 typedef typename base_class::item_counter item_counter ; ///< Item counting policy used
196 typedef typename maker::key_comparator key_comparator ; ///< key compare functor
197 typedef typename base_class::memory_model memory_model ; ///< Memory ordering. See cds::opt::memory_model option
198 typedef typename traits::random_level_generator random_level_generator ; ///< random level generator
199 typedef typename traits::stat stat ; ///< internal statistics type
200 typedef typename traits::rcu_check_deadlock rcu_check_deadlock ; ///< Deadlock checking policy
204 typedef typename maker::node_type node_type;
205 typedef typename maker::node_allocator node_allocator;
207 typedef std::unique_ptr< node_type, typename maker::node_deallocator > scoped_node_ptr;
211 typedef typename base_class::rcu_lock rcu_lock; ///< RCU scoped lock
212 /// Group of \p extract_xxx functions do not require external locking
213 static CDS_CONSTEXPR const bool c_bExtractLockExternal = base_class::c_bExtractLockExternal;
215 /// pointer to extracted node
216 using exempt_ptr = cds::urcu::exempt_ptr< gc, node_type, value_type, typename maker::intrusive_traits::disposer >;
220 struct raw_ptr_converter
222 value_type * operator()( node_type * p ) const
224 return p ? &p->m_Value : nullptr;
227 value_type& operator()( node_type& n ) const
232 value_type const& operator()( node_type const& n ) const
240 /// Result of \p get(), \p get_with() functions - pointer to the node found
241 typedef cds::urcu::raw_ptr_adaptor< value_type, typename base_class::raw_ptr, raw_ptr_converter > raw_ptr;
245 unsigned int random_level()
247 return base_class::random_level();
257 /// Destructor destroys the set object
263 typedef skip_list::details::iterator< typename base_class::iterator > iterator;
265 /// Const iterator type
266 typedef skip_list::details::iterator< typename base_class::const_iterator > const_iterator;
268 /// Returns a forward iterator addressing the first element in a set
271 return iterator( base_class::begin() );
274 /// Returns a forward const iterator addressing the first element in a set
276 const_iterator begin() const
278 return const_iterator( base_class::begin() );
280 const_iterator cbegin() const
282 return const_iterator( base_class::cbegin() );
286 /// Returns a forward iterator that addresses the location succeeding the last element in a set.
289 return iterator( base_class::end() );
292 /// Returns a forward const iterator that addresses the location succeeding the last element in a set.
294 const_iterator end() const
296 return const_iterator( base_class::end() );
298 const_iterator cend() const
300 return const_iterator( base_class::cend() );
307 The function creates a node with copy of \p val value
308 and then inserts the node created into the set.
310 The type \p Q should contain as minimum the complete key for the node.
311 The object of \ref value_type should be constructible from a value of type \p Q.
312 In trivial case, \p Q is equal to \ref value_type.
314 RCU \p synchronize method can be called. RCU should not be locked.
316 Returns \p true if \p val is inserted into the set, \p false otherwise.
318 template <typename Q>
319 bool insert( Q const& val )
321 scoped_node_ptr sp( node_allocator().New( random_level(), val ));
322 if ( base_class::insert( *sp.get() )) {
331 The function allows to split creating of new item into two part:
332 - create item with key only
333 - insert new item into the set
334 - if inserting is success, calls \p f functor to initialize value-fields of \p val.
336 The functor signature is:
338 void func( value_type& val );
340 where \p val is the item inserted. User-defined functor \p f should guarantee that during changing
341 \p val no any other changes could be made on this set's item by concurrent threads.
342 The user-defined functor is called only if the inserting is success.
344 RCU \p synchronize method can be called. RCU should not be locked.
346 template <typename Q, typename Func>
347 bool insert( Q const& val, Func f )
349 scoped_node_ptr sp( node_allocator().New( random_level(), val ));
350 if ( base_class::insert( *sp.get(), [&f]( node_type& val ) { f( val.m_Value ); } )) {
359 The operation performs inserting or changing data with lock-free manner.
361 If \p val not found in the set, then the new item created from \p val
362 is inserted into the set iff \p bInsert is \p true.
363 Otherwise, the functor \p func is called with the item found.
364 The functor \p Func signature:
367 void operator()( bool bNew, value_type& item, const Q& val );
371 - \p bNew - \p true if the item has been inserted, \p false otherwise
372 - \p item - an item of the set
373 - \p val - argument \p val passed into the \p %update() function
375 The functor may change non-key fields of the \p item; however, \p func must guarantee
376 that during changing no any other modifications could be made on this item by concurrent threads.
378 RCU \p synchronize method can be called. RCU should not be locked.
380 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
381 \p second is true if new item has been added or \p false if the item with \p key
384 template <typename Q, typename Func>
385 std::pair<bool, bool> update( const Q& val, Func func, bool bInsert = true )
387 scoped_node_ptr sp( node_allocator().New( random_level(), val ));
388 std::pair<bool, bool> bRes = base_class::update( *sp,
389 [&func, &val](bool bNew, node_type& node, node_type&){ func( bNew, node.m_Value, val );}, bInsert );
390 if ( bRes.first && bRes.second )
395 template <typename Q, typename Func>
396 CDS_DEPRECATED("ensure() is deprecated, use update()")
397 std::pair<bool, bool> ensure( const Q& val, Func func )
399 return update( val, func, true );
403 /// Inserts data of type \ref value_type constructed with <tt>std::forward<Args>(args)...</tt>
405 Returns \p true if inserting successful, \p false otherwise.
407 RCU \p synchronize method can be called. RCU should not be locked.
409 template <typename... Args>
410 bool emplace( Args&&... args )
412 scoped_node_ptr sp( node_allocator().New( random_level(), std::forward<Args>(args)... ));
413 if ( base_class::insert( *sp.get() )) {
420 /// Delete \p key from the set
421 /** \anchor cds_nonintrusive_SkipListSet_rcu_erase_val
423 The item comparator should be able to compare the type \p value_type
426 RCU \p synchronize method can be called. RCU should not be locked.
428 Return \p true if key is found and deleted, \p false otherwise
430 template <typename Q>
431 bool erase( Q const& key )
433 return base_class::erase( key );
436 /// Deletes the item from the set using \p pred predicate for searching
438 The function is an analog of \ref cds_nonintrusive_SkipListSet_rcu_erase_val "erase(Q const&)"
439 but \p pred is used for key comparing.
440 \p Less functor has the interface like \p std::less.
441 \p Less must imply the same element order as the comparator used for building the set.
443 template <typename Q, typename Less>
444 bool erase_with( Q const& key, Less pred )
447 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >());
450 /// Delete \p key from the set
451 /** \anchor cds_nonintrusive_SkipListSet_rcu_erase_func
453 The function searches an item with key \p key, calls \p f functor
454 and deletes the item. If \p key is not found, the functor is not called.
456 The functor \p Func interface:
459 void operator()(value_type const& val);
463 Since the key of MichaelHashSet's \p value_type is not explicitly specified,
464 template parameter \p Q defines the key type searching in the list.
465 The list item comparator should be able to compare the type \p T of list item
468 RCU \p synchronize method can be called. RCU should not be locked.
470 Return \p true if key is found and deleted, \p false otherwise
474 template <typename Q, typename Func>
475 bool erase( Q const& key, Func f )
477 return base_class::erase( key, [&f]( node_type const& node) { f( node.m_Value ); } );
480 /// Deletes the item from the set using \p pred predicate for searching
482 The function is an analog of \ref cds_nonintrusive_SkipListSet_rcu_erase_func "erase(Q const&, Func)"
483 but \p pred is used for key comparing.
484 \p Less functor has the interface like \p std::less.
485 \p Less must imply the same element order as the comparator used for building the set.
487 template <typename Q, typename Less, typename Func>
488 bool erase_with( Q const& key, Less pred, Func f )
491 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
492 [&f]( node_type const& node) { f( node.m_Value ); } );
495 /// Extracts the item from the set with specified \p key
496 /** \anchor cds_nonintrusive_SkipListSet_rcu_extract
497 The function searches an item with key equal to \p key in the set,
498 unlinks it from the set, and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the item found.
499 If the item is not found the function returns an empty \p exempt_ptr
501 Note the compare functor from \p Traits class' template argument
502 should accept a parameter of type \p Q that can be not the same as \p value_type.
504 RCU \p synchronize method can be called. RCU should NOT be locked.
506 The function does not free the item found.
507 The item will be implicitly freed when the returned object is destroyed or when
508 its \p release() member function is called.
510 template <typename Q>
511 exempt_ptr extract( Q const& key )
513 return exempt_ptr( base_class::do_extract( key ));
516 /// Extracts the item from the set with comparing functor \p pred
518 The function is an analog of \p extract(Q const&) but \p pred predicate is used for key comparing.
519 \p Less has the semantics like \p std::less.
520 \p pred must imply the same element order as the comparator used for building the set.
522 template <typename Q, typename Less>
523 exempt_ptr extract_with( Q const& key, Less pred )
526 return exempt_ptr( base_class::do_extract_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >()));
529 /// Extracts an item with minimal key from the set
531 The function searches an item with minimal key, unlinks it,
532 and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the item.
533 If the skip-list is empty the function returns an empty \p exempt_ptr.
535 RCU \p synchronize method can be called. RCU should NOT be locked.
537 The function does not free the item found.
538 The item will be implicitly freed when the returned object is destroyed or when
539 its \p release() member function is called.
541 exempt_ptr extract_min()
543 return exempt_ptr( base_class::do_extract_min());
546 /// Extracts an item with maximal key from the set
548 The function searches an item with maximal key, unlinks it from the set,
549 and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the item.
550 If the skip-list is empty the function returns an empty \p exempt_ptr.
552 RCU \p synchronize method can be called. RCU should NOT be locked.
554 The function does not free the item found.
555 The item will be implicitly freed when the returned object is destroyed or when
556 its \p release() member function is called.
558 exempt_ptr extract_max()
560 return exempt_ptr( base_class::do_extract_max());
563 /// Find the key \p val
565 @anchor cds_nonintrusive_SkipListSet_rcu_find_func
567 The function searches the item with key equal to \p val and calls the functor \p f for item found.
568 The interface of \p Func functor is:
571 void operator()( value_type& item, Q& val );
574 where \p item is the item found, \p val is the <tt>find</tt> function argument.
576 The functor may change non-key fields of \p item. Note that the functor is only guarantee
577 that \p item cannot be disposed during functor is executing.
578 The functor does not serialize simultaneous access to the set's \p item. If such access is
579 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
581 The \p val argument is non-const since it can be used as \p f functor destination i.e., the functor
582 can modify both arguments.
584 Note the hash functor specified for class \p Traits template parameter
585 should accept a parameter of type \p Q that may be not the same as \p value_type.
587 The function applies RCU lock internally.
589 The function returns \p true if \p val is found, \p false otherwise.
591 template <typename Q, typename Func>
592 bool find( Q& val, Func f )
594 return base_class::find( val, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); });
597 template <typename Q, typename Func>
598 bool find( Q const& val, Func f )
600 return base_class::find( val, [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
604 /// Finds the key \p val using \p pred predicate for searching
606 The function is an analog of \ref cds_nonintrusive_SkipListSet_rcu_find_func "find(Q&, Func)"
607 but \p pred is used for key comparing.
608 \p Less functor has the interface like \p std::less.
609 \p Less must imply the same element order as the comparator used for building the set.
611 template <typename Q, typename Less, typename Func>
612 bool find_with( Q& val, Less pred, Func f )
615 return base_class::find_with( val, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
616 [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
619 template <typename Q, typename Less, typename Func>
620 bool find_with( Q const& val, Less pred, Func f )
623 return base_class::find_with( val, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >(),
624 [&f]( node_type& node, Q& v ) { f( node.m_Value, v ); } );
628 /// Checks whether the set contains \p key
630 The function searches the item with key equal to \p key
631 and returns \p true if it is found, and \p false otherwise.
633 The function applies RCU lock internally.
635 template <typename Q>
636 bool contains( Q const & key )
638 return base_class::contains( key );
641 template <typename Q>
642 CDS_DEPRECATED("deprecated, use contains()")
643 bool find( Q const & key )
645 return contains( key );
649 /// Checks whether the set contains \p key using \p pred predicate for searching
651 The function is similar to <tt>contains( key )</tt> but \p pred is used for key comparing.
652 \p Less functor has the interface like \p std::less.
653 \p Less must imply the same element order as the comparator used for building the set.
655 template <typename Q, typename Less>
656 bool contains( Q const& key, Less pred )
659 return base_class::contains( key, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >());
662 template <typename Q, typename Less>
663 CDS_DEPRECATED("deprecated, use contains()")
664 bool find_with( Q const& key, Less pred )
666 return contains( key, pred );
670 /// Finds \p key and return the item found
671 /** \anchor cds_nonintrusive_SkipListSet_rcu_get
672 The function searches the item with key equal to \p key and returns a \p raw_ptr object pointed to item found.
673 If \p key is not found it returns empty \p raw_ptr.
675 Note the compare functor in \p Traits class' template argument
676 should accept a parameter of type \p Q that can be not the same as \p value_type.
678 RCU should be locked before call of this function.
679 Returned item is valid only while RCU is locked:
681 typedef cds::container::SkipListSet< cds::urcu::gc< cds::urcu::general_buffered<> >, foo, my_traits > skip_list;
684 typename skip_list::raw_ptr pVal;
687 skip_list::rcu_lock lock;
689 pVal = theList.get( 5 );
695 // You can manually release pVal after RCU-locked section
699 template <typename Q>
700 raw_ptr get( Q const& key )
702 return raw_ptr( base_class::get( key ));
705 /// Finds the key \p val and return the item found
707 The function is an analog of \ref cds_nonintrusive_SkipListSet_rcu_get "get(Q const&)"
708 but \p pred is used for comparing the keys.
710 \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
712 \p pred must imply the same element order as the comparator used for building the set.
714 template <typename Q, typename Less>
715 raw_ptr get_with( Q const& val, Less pred )
718 return raw_ptr( base_class::get_with( val, cds::details::predicate_wrapper< node_type, Less, typename maker::value_accessor >() ));
721 /// Clears the set (non-atomic).
723 The function deletes all items from the set.
724 The function is not atomic, thus, in multi-threaded environment with parallel insertions
728 assert( set.empty() );
730 the assertion could be raised.
732 For each item the \ref disposer provided by \p Traits template parameter will be called.
739 /// Checks if the set is empty
742 return base_class::empty();
745 /// Returns item count in the set
747 The value returned depends on item counter type provided by \p Traits template parameter.
748 If it is atomicity::empty_item_counter this function always returns 0.
749 Therefore, the function is not suitable for checking the set emptiness, use \ref empty
750 member function for this purpose.
754 return base_class::size();
757 /// Returns const reference to internal statistics
758 stat const& statistics() const
760 return base_class::statistics();
764 }} // namespace cds::container
766 #endif // #ifndef CDSLIB_CONTAINER_SKIP_LIST_SET_RCU_H