3 #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_MAP_H
4 #define __CDS_CONTAINER_IMPL_SKIP_LIST_MAP_H
6 #include <cds/container/details/guarded_ptr_cast.h>
8 namespace cds { namespace container {
10 /// Lock-free skip-list map
11 /** @ingroup cds_nonintrusive_map
12 \anchor cds_nonintrusive_SkipListMap_hp
14 The implementation of well-known probabilistic data structure called skip-list
15 invented by W.Pugh in his papers:
16 - [1989] W.Pugh Skip Lists: A Probabilistic Alternative to Balanced Trees
17 - [1990] W.Pugh A Skip List Cookbook
19 A skip-list is a probabilistic data structure that provides expected logarithmic
20 time search without the need of rebalance. The skip-list is a collection of sorted
21 linked list. Nodes are ordered by key. Each node is linked into a subset of the lists.
22 Each list has a level, ranging from 0 to 32. The bottom-level list contains
23 all the nodes, and each higher-level list is a sublist of the lower-level lists.
24 Each node is created with a random top level (with a random height), and belongs
25 to all lists up to that level. The probability that a node has the height 1 is 1/2.
26 The probability that a node has the height N is 1/2 ** N (more precisely,
27 the distribution depends on an random generator provided, but our generators
30 The lock-free variant of skip-list is implemented according to book
31 - [2008] M.Herlihy, N.Shavit "The Art of Multiprocessor Programming",
32 chapter 14.4 "A Lock-Free Concurrent Skiplist"
35 - \p GC - Garbage collector used.
36 - \p K - type of a key to be stored in the list.
37 - \p T - type of a value to be stored in the list.
38 - \p Traits - map traits, default is \p skip_list::traits
39 It is possible to declare option-based list with \p cds::container::skip_list::make_traits metafunction
40 istead of \p Traits template argument.
42 Like STL map class, \p %SkipListMap stores the key-value pair as <tt>std:pair< K const, T></tt>.
44 @warning The skip-list requires up to 67 hazard pointers that may be critical for some GCs for which
45 the guard count is limited (like \p gc::HP). Those GCs should be explicitly initialized with
46 hazard pointer enough: \code cds::gc::HP myhp( 67 ) \endcode. Otherwise an run-time exception may be raised
47 when you try to create skip-list object.
49 @note There are several specializations of \p %SkipListMap for each \p GC. You should include:
50 - <tt><cds/container/skip_list_map_hp.h></tt> for \p gc::HP garbage collector
51 - <tt><cds/container/skip_list_map_dhp.h></tt> for \p gc::DHP garbage collector
52 - <tt><cds/container/skip_list_map_rcu.h></tt> for \ref cds_nonintrusive_SkipListMap_rcu "RCU type"
53 - <tt><cds/container/skip_list_map_nogc.h></tt> for \ref cds_nonintrusive_SkipListMap_nogc "non-deletable SkipListMap"
57 The class supports a forward iterator (\ref iterator and \ref const_iterator).
58 The iteration is ordered.
59 The iterator object is thread-safe: the element pointed by the iterator object is guarded,
60 so, the element cannot be reclaimed while the iterator object is alive.
61 However, passing an iterator object between threads is dangerous.
63 \warning Due to concurrent nature of skip-list map it is not guarantee that you can iterate
64 all elements in the map: any concurrent deletion can exclude the element
65 pointed by the iterator from the map, and your iteration can be terminated
66 before end of the map. Therefore, such iteration is more suitable for debugging purpose only
68 Remember, each iterator object requires 2 additional hazard pointers, that may be
69 a limited resource for \p GC like \p gc::HP (for gc::DHP the count of
72 The iterator class supports the following minimalistic interface:
79 iterator( iterator const& s);
81 value_type * operator ->() const;
82 value_type& operator *() const;
85 iterator& operator ++();
88 iterator& operator = (const iterator& src);
90 bool operator ==(iterator const& i ) const;
91 bool operator !=(iterator const& i ) const;
94 Note, the iterator object returned by \ref end, \ cend member functions points to \p nullptr and should not be dereferenced.
101 #ifdef CDS_DOXYGEN_INVOKED
102 typename Traits = skip_list::traits
108 #ifdef CDS_DOXYGEN_INVOKED
109 protected intrusive::SkipListSet< GC, std::pair<Key const, T>, Traits >
111 protected details::make_skip_list_map< GC, Key, T, Traits >::type
115 typedef details::make_skip_list_map< GC, Key, T, Traits > maker;
116 typedef typename maker::type base_class;
119 typedef GC gc; ///< Garbage collector
120 typedef Key key_type; ///< Key type
121 typedef T mapped_type; ///< Mapped type
122 typedef Traits traits; ///< Map traits
123 # ifdef CDS_DOXYGEN_INVOKED
124 typedef std::pair< K const, T> value_type; ///< Key-value pair to be stored in the map
126 typedef typename maker::value_type value_type;
129 typedef typename base_class::back_off back_off; ///< Back-off strategy
130 typedef typename traits::allocator allocator_type; ///< Allocator type used for allocate/deallocate the skip-list nodes
131 typedef typename base_class::item_counter item_counter; ///< Item counting policy used
132 typedef typename maker::key_comparator key_comparator; ///< key comparison functor
133 typedef typename base_class::memory_model memory_model; ///< Memory ordering, see \p cds::opt::memory_model
134 typedef typename traits::random_level_generator random_level_generator ; ///< random level generator
135 typedef typename traits::stat stat; ///< internal statistics type
139 typedef typename maker::node_type node_type;
140 typedef typename maker::node_allocator node_allocator;
142 typedef std::unique_ptr< node_type, typename maker::node_deallocator > scoped_node_ptr;
147 typedef cds::gc::guarded_ptr< gc, node_type, value_type, details::guarded_ptr_cast_set<node_type, value_type> > guarded_ptr;
151 unsigned int random_level()
153 return base_class::random_level();
163 /// Destructor destroys the set object
169 typedef skip_list::details::iterator< typename base_class::iterator > iterator;
171 /// Const iterator type
172 typedef skip_list::details::iterator< typename base_class::const_iterator > const_iterator;
174 /// Returns a forward iterator addressing the first element in a map
177 return iterator( base_class::begin() );
180 /// Returns a forward const iterator addressing the first element in a map
181 const_iterator begin() const
185 /// Returns a forward const iterator addressing the first element in a map
186 const_iterator cbegin() const
188 return const_iterator( base_class::cbegin() );
191 /// Returns a forward iterator that addresses the location succeeding the last element in a map.
194 return iterator( base_class::end() );
197 /// Returns a forward const iterator that addresses the location succeeding the last element in a map.
198 const_iterator end() const
202 /// Returns a forward const iterator that addresses the location succeeding the last element in a map.
203 const_iterator cend() const
205 return const_iterator( base_class::cend() );
209 /// Inserts new node with key and default value
211 The function creates a node with \p key and default value, and then inserts the node created into the map.
214 - The \p key_type should be constructible from a value of type \p K.
215 In trivial case, \p K is equal to \p key_type.
216 - The \p mapped_type should be default-constructible.
218 Returns \p true if inserting successful, \p false otherwise.
220 template <typename K>
221 bool insert( K const& key )
223 return insert_key( key, [](value_type&){} );
228 The function creates a node with copy of \p val value
229 and then inserts the node created into the map.
232 - The \p key_type should be constructible from \p key of type \p K.
233 - The \p value_type should be constructible from \p val of type \p V.
235 Returns \p true if \p val is inserted into the set, \p false otherwise.
237 template <typename K, typename V>
238 bool insert( K const& key, V const& val )
240 return insert_key( key, [&val](value_type& item) { item.second = val ; } );
243 /// Inserts new node and initialize it by a functor
245 This function inserts new node with key \p key and if inserting is successful then it calls
246 \p func functor with signature
249 void operator()( value_type& item );
253 The argument \p item of user-defined functor \p func is the reference
254 to the map's item inserted:
255 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
256 - <tt>item.second</tt> is a reference to item's value that may be changed.
258 \p key_type should be constructible from value of type \p K.
260 The function allows to split creating of new item into two part:
261 - create item from \p key;
262 - insert new item into the map;
263 - if inserting is successful, initialize the value of item by calling \p func functor
265 This can be useful if complete initialization of object of \p value_type is heavyweight and
266 it is preferable that the initialization should be completed only if inserting is successful.
268 template <typename K, typename Func>
269 bool insert_key( const K& key, Func func )
271 scoped_node_ptr pNode( node_allocator().New( random_level(), key ));
272 if ( base_class::insert( *pNode, [&func]( node_type& item ) { func( item.m_Value ); } )) {
279 /// For key \p key inserts data of type \p value_type created in-place from <tt>std::forward<Args>(args)...</tt>
281 Returns \p true if inserting successful, \p false otherwise.
283 template <typename K, typename... Args>
284 bool emplace( K&& key, Args&&... args )
286 scoped_node_ptr pNode( node_allocator().New( random_level(), std::forward<K>(key), std::forward<Args>(args)... ));
287 if ( base_class::insert( *pNode )) {
294 /// Ensures that the \p key exists in the map
296 The operation performs inserting or changing data with lock-free manner.
298 If the \p key not found in the map, then the new item created from \p key
299 is inserted into the map (note that in this case the \ref key_type should be
300 constructible from type \p K).
301 Otherwise, the functor \p func is called with item found.
302 The functor \p Func may be a function with signature:
304 void func( bool bNew, value_type& item );
309 void operator()( bool bNew, value_type& item );
314 - \p bNew - \p true if the item has been inserted, \p false otherwise
315 - \p item - item of the list
317 The functor may change any fields of the \p item.second that is \ref value_type.
319 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
320 \p second is true if new item has been added or \p false if the item with \p key
321 already is in the list.
323 @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
325 template <typename K, typename Func>
326 std::pair<bool, bool> ensure( K const& key, Func func )
328 scoped_node_ptr pNode( node_allocator().New( random_level(), key ));
329 std::pair<bool, bool> res = base_class::ensure( *pNode,
330 [&func](bool bNew, node_type& item, node_type const& ){ func( bNew, item.m_Value ); }
332 if ( res.first && res.second )
337 /// Delete \p key from the map
338 /** \anchor cds_nonintrusive_SkipListMap_erase_val
340 Return \p true if \p key is found and deleted, \p false otherwise
342 template <typename K>
343 bool erase( K const& key )
345 return base_class::erase(key);
348 /// Deletes the item from the map using \p pred predicate for searching
350 The function is an analog of \ref cds_nonintrusive_SkipListMap_erase_val "erase(K const&)"
351 but \p pred is used for key comparing.
352 \p Less functor has the interface like \p std::less.
353 \p Less must imply the same element order as the comparator used for building the map.
355 template <typename K, typename Less>
356 bool erase_with( K const& key, Less pred )
359 return base_class::erase_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::key_accessor >());
362 /// Delete \p key from the map
363 /** \anchor cds_nonintrusive_SkipListMap_erase_func
365 The function searches an item with key \p key, calls \p f functor
366 and deletes the item. If \p key is not found, the functor is not called.
368 The functor \p Func interface:
371 void operator()(value_type& item) { ... }
375 Return \p true if key is found and deleted, \p false otherwise
377 template <typename K, typename Func>
378 bool erase( K const& key, Func f )
380 return base_class::erase( key, [&f]( node_type& node) { f( node.m_Value ); } );
383 /// Deletes the item from the map using \p pred predicate for searching
385 The function is an analog of \ref cds_nonintrusive_SkipListMap_erase_func "erase(K const&, Func)"
386 but \p pred is used for key comparing.
387 \p Less functor has the interface like \p std::less.
388 \p Less must imply the same element order as the comparator used for building the map.
390 template <typename K, typename Less, typename Func>
391 bool erase_with( K const& key, Less pred, Func f )
394 return base_class::erase_with( key,
395 cds::details::predicate_wrapper< node_type, Less, typename maker::key_accessor >(),
396 [&f]( node_type& node) { f( node.m_Value ); } );
399 /// Extracts the item from the map with specified \p key
400 /** \anchor cds_nonintrusive_SkipListMap_hp_extract
401 The function searches an item with key equal to \p key in the map,
402 unlinks it from the map, and returns it in \p ptr parameter.
403 If the item with key equal to \p key is not found the function returns \p false.
405 Note the compare functor should accept a parameter of type \p K that can be not the same as \p key_type.
407 The item extracted is freed automatically by garbage collector \p GC
408 when returned \ref guarded_ptr object will be destroyed or released.
409 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
413 typedef cds::container::SkipListMap< cds::gc::HP, int, foo, my_traits > skip_list;
417 skip_list::guarded_ptr gp;
418 if ( theList.extract( gp, 5 ) ) {
422 // Destructor of gp releases internal HP guard and frees the pointer
426 template <typename K>
427 bool extract( guarded_ptr& ptr, K const& key )
429 return base_class::extract_( ptr.guard(), key, typename base_class::key_comparator() );
432 /// Extracts the item from the map with comparing functor \p pred
434 The function is an analog of \ref cds_nonintrusive_SkipListMap_hp_extract "extract(K const&)"
435 but \p pred predicate is used for key comparing.
437 \p Less functor has the semantics like \p std::less but should take arguments of type \ref key_type and \p K
439 \p pred must imply the same element order as the comparator used for building the map.
441 template <typename K, typename Less>
442 bool extract_with( guarded_ptr& ptr, K const& key, Less pred )
445 typedef cds::details::predicate_wrapper< node_type, Less, typename maker::key_accessor > wrapped_less;
446 return base_class::extract_( ptr.guard(), key, cds::opt::details::make_comparator_from_less<wrapped_less>() );
449 /// Extracts an item with minimal key from the map
451 The function searches an item with minimal key, unlinks it, and returns the item found in \p ptr parameter.
452 If the skip-list is empty the function returns \p false.
454 The item extracted is freed automatically by garbage collector \p GC
455 when returned \ref guarded_ptr object will be destroyed or released.
456 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
460 typedef cds::continer::SkipListMap< cds::gc::HP, int, foo, my_traits > skip_list;
464 skip_list::guarded_ptr gp;
465 if ( theList.extract_min( gp )) {
469 // Destructor of gp releases internal HP guard and then frees the pointer
473 bool extract_min( guarded_ptr& ptr)
475 return base_class::extract_min_( ptr.guard() );
478 /// Extracts an item with maximal key from the map
480 The function searches an item with maximal key, unlinks it, and returns the pointer to item found in \p ptr parameter.
481 If the skip-list is empty the function returns empty \p guarded_ptr.
483 The item found is freed by garbage collector \p GC automatically
484 when returned \ref guarded_ptr object will be destroyed or released.
485 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
489 typedef cds::container::SkipListMap< cds::gc::HP, int, foo, my_traits > skip_list;
493 skip_list::guarded_ptr gp;
494 if ( theList.extract_max( gp )) {
498 // Destructor of gp releases internal HP guard and then frees the pointer
502 bool extract_max( guarded_ptr& dest )
504 return base_class::extract_max_( dest.guard() );
507 /// Find the key \p key
508 /** \anchor cds_nonintrusive_SkipListMap_find_cfunc
510 The function searches the item with key equal to \p key and calls the functor \p f for item found.
511 The interface of \p Func functor is:
514 void operator()( value_type& item );
517 where \p item is the item found.
519 The functor may change \p item.second.
521 The function returns \p true if \p key is found, \p false otherwise.
523 template <typename K, typename Func>
524 bool find( K const& key, Func f )
526 return base_class::find( key, [&f](node_type& item, K const& ) { f( item.m_Value );});
529 /// Finds the key \p val using \p pred predicate for searching
531 The function is an analog of \ref cds_nonintrusive_SkipListMap_find_cfunc "find(K const&, Func)"
532 but \p pred is used for key comparing.
533 \p Less functor has the interface like \p std::less.
534 \p Less must imply the same element order as the comparator used for building the map.
536 template <typename K, typename Less, typename Func>
537 bool find_with( K const& key, Less pred, Func f )
540 return base_class::find_with( key,
541 cds::details::predicate_wrapper< node_type, Less, typename maker::key_accessor >(),
542 [&f](node_type& item, K const& ) { f( item.m_Value );});
545 /// Find the key \p key
546 /** \anchor cds_nonintrusive_SkipListMap_find_val
548 The function searches the item with key equal to \p key
549 and returns \p true if it is found, and \p false otherwise.
551 template <typename K>
552 bool find( K const& key )
554 return base_class::find( key );
557 /// Finds the key \p val using \p pred predicate for searching
559 The function is an analog of \ref cds_nonintrusive_SkipListMap_find_val "find(K const&)"
560 but \p pred is used for key comparing.
561 \p Less functor has the interface like \p std::less.
562 \p Less must imply the same element order as the comparator used for building the map.
564 template <typename K, typename Less>
565 bool find_with( K const& key, Less pred )
568 return base_class::find_with( key, cds::details::predicate_wrapper< node_type, Less, typename maker::key_accessor >() );
571 /// Finds the key \p key and return the item found
572 /** \anchor cds_nonintrusive_SkipListMap_hp_get
573 The function searches the item with key equal to \p key
574 and assigns the item found to guarded pointer \p ptr.
575 The function returns \p true if \p key is found, and \p false otherwise.
576 If \p key is not found the \p ptr parameter is not changed.
578 It is safe when a concurrent thread erases the item returned in \p ptr guarded pointer.
579 In this case the item will be freed later by garbage collector \p GC automatically
580 when \p guarded_ptr object will be destroyed or released.
581 @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
585 typedef cds::container::SkipListMap< cds::gc::HP, int, foo, my_traits > skip_list;
589 skip_list::guarded_ptr gp;
590 if ( theList.get( gp, 5 ) ) {
594 // Destructor of guarded_ptr releases internal HP guard
598 Note the compare functor specified for class \p Traits template parameter
599 should accept a parameter of type \p K that can be not the same as \p value_type.
601 template <typename K>
602 bool get( guarded_ptr& ptr, K const& key )
604 return base_class::get_with_( ptr.guard(), key, typename base_class::key_comparator() );
607 /// Finds the key \p key and return the item found
609 The function is an analog of \ref cds_nonintrusive_SkipListMap_hp_get "get( guarded_ptr& ptr, K const&)"
610 but \p pred is used for comparing the keys.
612 \p Less functor has the semantics like \p std::less but should take arguments of type \ref key_type and \p K
614 \p pred must imply the same element order as the comparator used for building the map.
616 template <typename K, typename Less>
617 bool get_with( guarded_ptr& ptr, K const& key, Less pred )
620 typedef cds::details::predicate_wrapper< node_type, Less, typename maker::key_accessor > wrapped_less;
621 return base_class::get_with_( ptr.guard(), key, cds::opt::details::make_comparator_from_less< wrapped_less >());
630 /// Checks if the map is empty
633 return base_class::empty();
636 /// Returns item count in the map
639 return base_class::size();
642 /// Returns const reference to internal statistics
643 stat const& statistics() const
645 return base_class::statistics();
648 }} // namespace cds::container
650 #endif // #ifndef __CDS_CONTAINER_IMPL_SKIP_LIST_MAP_H