3 #ifndef CDSLIB_CONTAINER_IMPL_MICHAEL_KVLIST_H
4 #define CDSLIB_CONTAINER_IMPL_MICHAEL_KVLIST_H
7 #include <cds/container/details/guarded_ptr_cast.h>
9 namespace cds { namespace container {
11 /// Michael's ordered list fo key-value pair
12 /** @ingroup cds_nonintrusive_list
13 \anchor cds_nonintrusive_MichaelKVList_gc
15 This is key-value variation of non-intrusive MichaelList.
16 Like standard container, this implementation split a value stored into two part -
17 constant key and alterable value.
19 Usually, ordered single-linked list is used as a building block for the hash table implementation.
20 The complexity of searching is <tt>O(N)</tt> where \p N is the item count in the list, not in the
24 - \p GC - garbage collector used
25 - \p Key - key type of an item stored in the list. It should be copy-constructible
26 - \p Value - value type stored in a list
27 - \p Traits - type traits, default is \p michael_list::traits
29 It is possible to declare option-based list with \p cds::container::michael_list::make_traits metafunction istead of \p Traits template
30 argument. For example, the following traits-based declaration of \p gc::HP Michael's list
32 #include <cds/container/michael_kvlist_hp.h>
33 // Declare comparator for the item
35 int operator ()( int i1, int i2 )
42 struct my_traits: public cds::container::michael_list::traits
44 typedef my_compare compare;
47 // Declare traits-based list
48 typedef cds::container::MichaelKVList< cds::gc::HP, int, int, my_traits > traits_based_list;
50 is equivalent for the following option-based list
52 #include <cds/container/michael_kvlist_hp.h>
54 // my_compare is the same
56 // Declare option-based list
57 typedef cds::container::MichaelKVList< cds::gc::HP, int, int,
58 typename cds::container::michael_list::make_traits<
59 cds::container::opt::compare< my_compare > // item comparator option
65 There are different specializations of this template for each garbage collecting schema used.
66 You should include appropriate .h-file depending on GC you are using:
67 - for gc::HP: \code #include <cds/container/michael_kvlist_hp.h> \endcode
68 - for gc::DHP: \code #include <cds/container/michael_kvlist_dhp.h> \endcode
69 - for \ref cds_urcu_desc "RCU": \code #include <cds/container/michael_kvlist_rcu.h> \endcode
70 - for gc::nogc: \code #include <cds/container/michael_kvlist_nogc.h> \endcode
76 #ifdef CDS_DOXYGEN_INVOKED
77 typename Traits = michael_list::traits
83 #ifdef CDS_DOXYGEN_INVOKED
84 protected intrusive::MichaelList< GC, implementation_defined, Traits >
86 protected details::make_michael_kvlist< GC, Key, Value, Traits >::type
90 typedef details::make_michael_kvlist< GC, Key, Value, Traits > maker;
91 typedef typename maker::type base_class;
95 #ifdef CDS_DOXYGEN_INVOKED
96 typedef Key key_type ; ///< Key type
97 typedef Value mapped_type ; ///< Type of value stored in the list
98 typedef std::pair<key_type const, mapped_type> value_type ; ///< key/value pair stored in the list
100 typedef typename maker::key_type key_type;
101 typedef typename maker::value_type mapped_type;
102 typedef typename maker::pair_type value_type;
105 typedef typename base_class::gc gc; ///< Garbage collector used
106 typedef typename base_class::back_off back_off; ///< Back-off strategy used
107 typedef typename maker::allocator_type allocator_type; ///< Allocator type used for allocate/deallocate the nodes
108 typedef typename base_class::item_counter item_counter; ///< Item counting policy used
109 typedef typename maker::key_comparator key_comparator; ///< key comparison functor
110 typedef typename base_class::memory_model memory_model; ///< Memory ordering. See cds::opt::memory_model option
114 typedef typename base_class::value_type node_type;
115 typedef typename maker::cxx_allocator cxx_allocator;
116 typedef typename maker::node_deallocator node_deallocator;
117 typedef typename maker::intrusive_traits::compare intrusive_key_comparator;
119 typedef typename base_class::atomic_node_ptr head_type;
124 typedef typename gc::template guarded_ptr< node_type, value_type, details::guarded_ptr_cast_map<node_type, value_type> > guarded_ptr;
128 template <typename K>
129 static node_type * alloc_node(const K& key)
131 return cxx_allocator().New( key );
134 template <typename K, typename V>
135 static node_type * alloc_node( const K& key, const V& val )
137 return cxx_allocator().New( key, val );
140 template <typename K, typename... Args>
141 static node_type * alloc_node( K&& key, Args&&... args )
143 return cxx_allocator().MoveNew( std::forward<K>(key), std::forward<Args>(args)...);
146 static void free_node( node_type * pNode )
148 cxx_allocator().Delete( pNode );
151 struct node_disposer {
152 void operator()( node_type * pNode )
157 typedef std::unique_ptr< node_type, node_disposer > scoped_node_ptr;
161 return base_class::m_pHead;
164 head_type const& head() const
166 return base_class::m_pHead;
172 template <bool IsConst>
173 class iterator_type: protected base_class::template iterator_type<IsConst>
175 typedef typename base_class::template iterator_type<IsConst> iterator_base;
177 iterator_type( head_type const& pNode )
178 : iterator_base( pNode )
181 friend class MichaelKVList;
184 typedef typename cds::details::make_const_type<mapped_type, IsConst>::reference value_ref;
185 typedef typename cds::details::make_const_type<mapped_type, IsConst>::pointer value_ptr;
187 typedef typename cds::details::make_const_type<value_type, IsConst>::reference pair_ref;
188 typedef typename cds::details::make_const_type<value_type, IsConst>::pointer pair_ptr;
193 iterator_type( iterator_type const& src )
194 : iterator_base( src )
197 key_type const& key() const
199 typename iterator_base::value_ptr p = iterator_base::operator ->();
200 assert( p != nullptr );
201 return p->m_Data.first;
204 pair_ptr operator ->() const
206 typename iterator_base::value_ptr p = iterator_base::operator ->();
207 return p ? &(p->m_Data) : nullptr;
210 pair_ref operator *() const
212 typename iterator_base::value_ref p = iterator_base::operator *();
216 value_ref val() const
218 typename iterator_base::value_ptr p = iterator_base::operator ->();
219 assert( p != nullptr );
220 return p->m_Data.second;
224 iterator_type& operator ++()
226 iterator_base::operator ++();
231 bool operator ==(iterator_type<C> const& i ) const
233 return iterator_base::operator ==(i);
236 bool operator !=(iterator_type<C> const& i ) const
238 return iterator_base::operator !=(i);
246 The forward iterator for Michael's list has some features:
247 - it has no post-increment operator
248 - to protect the value, the iterator contains a GC-specific guard + another guard is required locally for increment operator.
249 For some GC (\p gc::HP), a guard is limited resource per thread, so an exception (or assertion) "no free guard"
250 may be thrown if a limit of guard count per thread is exceeded.
251 - The iterator cannot be moved across thread boundary since it contains GC's guard that is thread-private GC data.
252 - Iterator ensures thread-safety even if you delete the item that iterator points to. However, in case of concurrent
253 deleting operations it is no guarantee that you iterate all item in the list.
255 Therefore, the use of iterators in concurrent environment is not good idea. Use the iterator on the concurrent container
256 for debug purpose only.
258 The iterator interface to access item data:
259 - <tt> operator -> </tt> - returns a pointer to \ref value_type for iterator
260 - <tt> operator *</tt> - returns a reference (a const reference for \p const_iterator) to \ref value_type for iterator
261 - <tt> const key_type& key() </tt> - returns a key reference for iterator
262 - <tt> mapped_type& val() </tt> - retuns a value reference for iterator (const reference for \p const_iterator)
264 For both functions the iterator should not be equal to <tt> end() </tt>
266 typedef iterator_type<false> iterator;
268 /// Const forward iterator
270 For iterator's features and requirements see \ref iterator
272 typedef iterator_type<true> const_iterator;
274 /// Returns a forward iterator addressing the first element in a list
276 For empty list \code begin() == end() \endcode
280 return iterator( head() );
283 /// Returns an iterator that addresses the location succeeding the last element in a list
285 Do not use the value returned by <tt>end</tt> function to access any item.
286 Internally, <tt>end</tt> returning value equals to \p nullptr.
288 The returned value can be used only to control reaching the end of the list.
289 For empty list \code begin() == end() \endcode
296 /// Returns a forward const iterator addressing the first element in a list
298 const_iterator begin() const
300 return const_iterator( head() );
302 const_iterator cbegin() const
304 return const_iterator( head() );
308 /// Returns an const iterator that addresses the location succeeding the last element in a list
310 const_iterator end() const
312 return const_iterator();
314 const_iterator cend() const
316 return const_iterator();
321 /// Default constructor
323 Initializes empty list
337 /// Inserts new node with key and default value
339 The function creates a node with \p key and default value, and then inserts the node created into the list.
342 - The \p key_type should be constructible from value of type \p K.
343 In trivial case, \p K is equal to \p key_type.
344 - The \p mapped_type should be default-constructible.
346 Returns \p true if inserting successful, \p false otherwise.
348 template <typename K>
349 bool insert( const K& key )
351 return insert_at( head(), key );
354 /// Inserts new node with a key and a value
356 The function creates a node with \p key and value \p val, and then inserts the node created into the list.
359 - The \p key_type should be constructible from \p key of type \p K.
360 - The \p mapped_type should be constructible from \p val of type \p V.
362 Returns \p true if inserting successful, \p false otherwise.
364 template <typename K, typename V>
365 bool insert( const K& key, const V& val )
367 // We cannot use insert with functor here
368 // because we cannot lock inserted node for updating
369 // Therefore, we use separate function
370 return insert_at( head(), key, val );
373 /// Inserts new node and initialize it by a functor
375 This function inserts new node with key \p key and if inserting is successful then it calls
376 \p func functor with signature
379 void operator()( value_type& item );
383 The argument \p item of user-defined functor \p func is the reference
384 to the item inserted. <tt>item.second</tt> is a reference to item's value that may be changed.
385 User-defined functor \p func should guarantee that during changing item's value no any other changes
386 could be made on this list's item by concurrent threads.
387 The user-defined functor is called only if inserting is successful.
389 The \p key_type should be constructible from value of type \p K.
391 The function allows to split creating of new item into two part:
392 - create a new item from \p key;
393 - insert the new item into the list;
394 - if inserting is successful, initialize the value of item by calling \p func functor
396 This can be useful if complete initialization of object of \p mapped_type is heavyweight and
397 it is preferable that the initialization should be completed only if inserting is successful.
399 @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
401 template <typename K, typename Func>
402 bool insert_with( const K& key, Func func )
404 return insert_with_at( head(), key, func );
407 /// Updates data by \p key
409 The operation performs inserting or replacing the element with lock-free manner.
411 If the \p key not found in the list, then the new item created from \p key
412 will be inserted iff \p bAllowInsert is \p true.
413 (note that in this case the \ref key_type should be constructible from type \p K).
414 Otherwise, if \p key is found, the functor \p func is called with item found.
416 The functor \p Func signature is:
419 void operator()( bool bNew, value_type& item );
423 - \p bNew - \p true if the item has been inserted, \p false otherwise
424 - \p item - the item found or inserted
426 The functor may change any fields of the \p item.second of \p mapped_type;
427 however, \p func must guarantee that during changing no any other modifications
428 could be made on this item by concurrent threads.
430 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
431 \p second is true if new item has been added or \p false if the item with \p key
434 @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
436 template <typename K, typename Func>
437 std::pair<bool, bool> update( K const& key, Func f, bool bAllowInsert = true )
439 return update_at( head(), key, f, bAllowInsert );
443 template <typename K, typename Func>
444 std::pair<bool, bool> ensure( K const& key, Func f )
446 return update( key, f, true );
450 /// Inserts a new node using move semantics
452 \p key_type field of new item is constructed from \p key argument,
453 \p mapped_type field is done from \p args.
455 Returns \p true if inserting successful, \p false otherwise.
457 template <typename K, typename... Args>
458 bool emplace( K&& key, Args&&... args )
460 return emplace_at( head(), std::forward<K>(key), std::forward<Args>(args)... );
463 /// Deletes \p key from the list
464 /** \anchor cds_nonintrusive_MichaelKVList_hp_erase_val
466 Returns \p true if \p key is found and has been deleted, \p false otherwise
468 template <typename K>
469 bool erase( K const& key )
471 return erase_at( head(), key, intrusive_key_comparator() );
474 /// Deletes the item from the list using \p pred predicate for searching
476 The function is an analog of \ref cds_nonintrusive_MichaelKVList_hp_erase_val "erase(K const&)"
477 but \p pred is used for key comparing.
478 \p Less functor has the interface like \p std::less.
479 \p pred must imply the same element order as the comparator used for building the list.
481 template <typename K, typename Less>
482 bool erase_with( K const& key, Less pred )
485 return erase_at( head(), key, typename maker::template less_wrapper<Less>::type() );
488 /// Deletes \p key from the list
489 /** \anchor cds_nonintrusive_MichaelKVList_hp_erase_func
490 The function searches an item with key \p key, calls \p f functor
491 and deletes the item. If \p key is not found, the functor is not called.
493 The functor \p Func interface:
496 void operator()(value_type& val) { ... }
500 Return \p true if key is found and deleted, \p false otherwise
504 template <typename K, typename Func>
505 bool erase( K const& key, Func f )
507 return erase_at( head(), key, intrusive_key_comparator(), f );
510 /// Deletes the item from the list using \p pred predicate for searching
512 The function is an analog of \ref cds_nonintrusive_MichaelKVList_hp_erase_func "erase(K const&, Func)"
513 but \p pred is used for key comparing.
514 \p Less functor has the interface like \p std::less.
515 \p pred must imply the same element order as the comparator used for building the list.
517 template <typename K, typename Less, typename Func>
518 bool erase_with( K const& key, Less pred, Func f )
521 return erase_at( head(), key, typename maker::template less_wrapper<Less>::type(), f );
524 /// Extracts the item from the list with specified \p key
525 /** \anchor cds_nonintrusive_MichaelKVList_hp_extract
526 The function searches an item with key equal to \p key,
527 unlinks it from the list, and returns it as \p guarded_ptr.
528 If \p key is not found the function returns an empty guarded pointer.
530 Note the compare functor should accept a parameter of type \p K that can be not the same as \p key_type.
532 The \p disposer specified in \p Traits class template parameter is called automatically
533 by garbage collector \p GC specified in class' template parameters when returned \p guarded_ptr object
534 will be destroyed or released.
535 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
539 typedef cds::container::MichaelKVList< cds::gc::HP, int, foo, my_traits > ord_list;
543 ord_list::guarded_ptr gp(theList.extract( 5 ));
548 // Destructor of gp releases internal HP guard
552 template <typename K>
553 guarded_ptr extract( K const& key )
556 extract_at( head(), gp.guard(), key, intrusive_key_comparator() );
560 /// Extracts the item from the list with comparing functor \p pred
562 The function is an analog of \ref cds_nonintrusive_MichaelKVList_hp_extract "extract(K const&)"
563 but \p pred predicate is used for key comparing.
565 \p Less functor has the semantics like \p std::less but should take arguments of type \ref key_type and \p K
567 \p pred must imply the same element order as the comparator used for building the list.
569 template <typename K, typename Less>
570 guarded_ptr extract_with( K const& key, Less pred )
574 extract_at( head(), gp.guard(), key, typename maker::template less_wrapper<Less>::type() );
578 /// Checks whether the list contains \p key
580 The function searches the item with key equal to \p key
581 and returns \p true if it is found, and \p false otherwise.
583 template <typename Q>
584 bool contains( Q const& key )
586 return find_at( head(), key, intrusive_key_comparator() );
590 template <typename Q>
591 bool find( Q const& key )
593 return contains( key );
597 /// Checks whether the map contains \p key using \p pred predicate for searching
599 The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
600 \p Less functor has the interface like \p std::less.
601 \p Less must imply the same element order as the comparator used for building the list.
603 template <typename Q, typename Less>
604 bool contains( Q const& key, Less pred )
607 return find_at( head(), key, typename maker::template less_wrapper<Less>::type() );
611 template <typename Q, typename Less>
612 bool find_with( Q const& key, Less pred )
615 return contains( key, pred );
619 /// Finds the key \p key and performs an action with it
620 /** \anchor cds_nonintrusive_MichaelKVList_hp_find_func
621 The function searches an item with key equal to \p key and calls the functor \p f for the item found.
622 The interface of \p Func functor is:
625 void operator()( value_type& item );
628 where \p item is the item found.
630 The functor may change <tt>item.second</tt> that is reference to value of node.
631 Note that the function is only guarantee that \p item cannot be deleted during functor is executing.
632 The function does not serialize simultaneous access to the list \p item. If such access is
633 possible you must provide your own synchronization schema to exclude unsafe item modifications.
635 The function returns \p true if \p key is found, \p false otherwise.
637 template <typename Q, typename Func>
638 bool find( Q const& key, Func f )
640 return find_at( head(), key, intrusive_key_comparator(), f );
643 /// Finds the key \p val using \p pred predicate for searching
645 The function is an analog of \ref cds_nonintrusive_MichaelKVList_hp_find_func "find(Q&, Func)"
646 but \p pred is used for key comparing.
647 \p Less functor has the interface like \p std::less.
648 \p pred must imply the same element order as the comparator used for building the list.
650 template <typename Q, typename Less, typename Func>
651 bool find_with( Q const& key, Less pred, Func f )
654 return find_at( head(), key, typename maker::template less_wrapper<Less>::type(), f );
657 /// Finds the \p key and return the item found
658 /** \anchor cds_nonintrusive_MichaelKVList_hp_get
659 The function searches the item with key equal to \p key
660 and returns it as \p guarded_ptr.
661 If \p key is not found the function returns an empty guarded pointer.
663 The \p disposer specified in \p Traits class template parameter is called
664 by garbage collector \p GC automatically when returned \p guarded_ptr object
665 will be destroyed or released.
666 @note Each \p guarded_ptr object uses one GC's guard which can be limited resource.
670 typedef cds::container::MichaelKVList< cds::gc::HP, int, foo, my_traits > ord_list;
674 ord_list::guarded_ptr gp(theList.get( 5 ));
679 // Destructor of guarded_ptr releases internal HP guard
683 Note the compare functor specified for class \p Traits template parameter
684 should accept a parameter of type \p K that can be not the same as \p key_type.
686 template <typename K>
687 guarded_ptr get( K const& key )
690 get_at( head(), gp.guard(), key, intrusive_key_comparator() );
694 /// Finds the \p key and return the item found
696 The function is an analog of \ref cds_nonintrusive_MichaelKVList_hp_get "get( guarded_ptr& ptr, K const&)"
697 but \p pred is used for comparing the keys.
699 \p Less functor has the semantics like \p std::less but should take arguments of type \ref key_type and \p K
701 \p pred must imply the same element order as the comparator used for building the list.
703 template <typename K, typename Less>
704 guarded_ptr get_with( K const& key, Less pred )
708 get_at( head(), gp.guard(), key, typename maker::template less_wrapper<Less>::type() );
712 /// Checks if the list is empty
715 return base_class::empty();
718 /// Returns list's item count
720 The value returned depends on item counter provided by \p Traits. For \p atomicity::empty_item_counter,
721 this function always returns 0.
723 @note Even if you use real item counter and it returns 0, this fact is not mean that the list
724 is empty. To check list emptyness use \p empty() method.
728 return base_class::size();
739 bool insert_node_at( head_type& refHead, node_type * pNode )
741 assert( pNode != nullptr );
742 scoped_node_ptr p( pNode );
743 if ( base_class::insert_at( refHead, *pNode )) {
750 template <typename K>
751 bool insert_at( head_type& refHead, const K& key )
753 return insert_node_at( refHead, alloc_node( key ));
756 template <typename K, typename V>
757 bool insert_at( head_type& refHead, const K& key, const V& val )
759 return insert_node_at( refHead, alloc_node( key, val ));
762 template <typename K, typename Func>
763 bool insert_with_at( head_type& refHead, const K& key, Func f )
765 scoped_node_ptr pNode( alloc_node( key ));
767 if ( base_class::insert_at( refHead, *pNode, [&f](node_type& node){ f( node.m_Data ); })) {
774 template <typename K, typename... Args>
775 bool emplace_at( head_type& refHead, K&& key, Args&&... args )
777 return insert_node_at( refHead, alloc_node( std::forward<K>(key), std::forward<Args>(args)... ));
780 template <typename K, typename Func>
781 std::pair<bool, bool> update_at( head_type& refHead, const K& key, Func f, bool bAllowInsert )
783 scoped_node_ptr pNode( alloc_node( key ));
785 std::pair<bool, bool> ret = base_class::update_at( refHead, *pNode,
786 [&f]( bool bNew, node_type& node, node_type& ){ f( bNew, node.m_Data ); },
788 if ( ret.first && ret.second )
794 template <typename K, typename Compare>
795 bool erase_at( head_type& refHead, K const& key, Compare cmp )
797 return base_class::erase_at( refHead, key, cmp );
800 template <typename K, typename Compare, typename Func>
801 bool erase_at( head_type& refHead, K const& key, Compare cmp, Func f )
803 return base_class::erase_at( refHead, key, cmp, [&f]( node_type const & node ){ f( const_cast<value_type&>(node.m_Data)); });
805 template <typename K, typename Compare>
806 bool extract_at( head_type& refHead, typename guarded_ptr::native_guard& guard, K const& key, Compare cmp )
808 return base_class::extract_at( refHead, guard, key, cmp );
811 template <typename K, typename Compare>
812 bool find_at( head_type& refHead, K const& key, Compare cmp )
814 return base_class::find_at( refHead, key, cmp );
817 template <typename K, typename Compare, typename Func>
818 bool find_at( head_type& refHead, K& key, Compare cmp, Func f )
820 return base_class::find_at( refHead, key, cmp, [&f](node_type& node, K const&){ f( node.m_Data ); });
823 template <typename K, typename Compare>
824 bool get_at( head_type& refHead, typename guarded_ptr::native_guard& guard, K const& key, Compare cmp )
826 return base_class::get_at( refHead, guard, key, cmp );
832 }} // namespace cds::container
834 #endif // #ifndef CDSLIB_CONTAINER_IMPL_MICHAEL_KVLIST_H