3 #ifndef CDSLIB_CONTAINER_IMPL_BRONSON_AVLTREE_MAP_RCU_H
4 #define CDSLIB_CONTAINER_IMPL_BRONSON_AVLTREE_MAP_RCU_H
6 #include <type_traits> // is_base_of
7 #include <cds/container/details/bronson_avltree_base.h>
8 #include <cds/urcu/details/check_deadlock.h>
9 #include <cds/urcu/exempt_ptr.h>
11 namespace cds { namespace container {
13 /// Bronson et al AVL-tree (RCU specialization for storing pointer to values)
14 /** @ingroup cds_nonintrusive_map
15 @ingroup cds_nonintrusive_tree
16 @headerfile cds/container/bronson_avltree_map_rcu.h
17 @anchor cds_container_BronsonAVLTreeMap_rcu_ptr
19 This is the specialization of \ref cds_container_BronsonAVLTreeMap_rcu "RCU-based Bronson et al AVL-tree"
20 for "key -> value pointer" map. This specialization stores the pointer to user-allocated values instead of the copy
21 of the value. When a tree node is removed, the algorithm does not free the value pointer directly, instead, it call
22 the disposer functor provided by \p Traits template parameter.
24 <b>Template arguments</b>:
25 - \p RCU - one of \ref cds_urcu_gc "RCU type"
27 - \p T - value type to be stored in tree's nodes. Note, the specialization stores the pointer to user-allocated
29 - \p Traits - tree traits, default is \p bronson_avltree::traits
30 It is possible to declare option-based tree with \p bronson_avltree::make_traits metafunction
31 instead of \p Traits template argument.
33 @note Before including <tt><cds/container/bronson_avltree_map_rcu.h></tt> you should include appropriate RCU header file,
34 see \ref cds_urcu_gc "RCU type" for list of existing RCU class and corresponding header files.
40 # ifdef CDS_DOXYGEN_INVOKED
41 typename Traits = bronson_avltree::traits
46 class BronsonAVLTreeMap< cds::urcu::gc<RCU>, Key, T*, Traits >
49 typedef cds::urcu::gc<RCU> gc; ///< RCU Garbage collector
50 typedef Key key_type; ///< type of a key stored in the map
51 typedef T * mapped_type; ///< type of value stored in the map
52 typedef Traits traits; ///< Traits template parameter
54 # ifdef CDS_DOXYGEN_INVOKED
55 typedef implementation_defined key_comparator; ///< key compare functor based on \p Traits::compare and \p Traits::less
57 typedef typename opt::details::make_comparator< key_type, traits >::type key_comparator;
59 typedef typename traits::item_counter item_counter; ///< Item counting policy
60 typedef typename traits::memory_model memory_model; ///< Memory ordering, see \p cds::opt::memory_model option
61 typedef typename traits::node_allocator node_allocator_type; ///< allocator for maintaining internal nodes
62 typedef typename traits::stat stat; ///< internal statistics
63 typedef typename traits::rcu_check_deadlock rcu_check_deadlock; ///< Deadlock checking policy
64 typedef typename traits::back_off back_off; ///< Back-off strategy
65 typedef typename traits::disposer disposer; ///< Value disposer
66 typedef typename traits::sync_monitor sync_monitor; ///< @ref cds_sync_monitor "Synchronization monitor" type for node-level locking
68 /// Enabled or disabled @ref bronson_avltree::relaxed_insert "relaxed insertion"
69 static CDS_CONSTEXPR bool const c_bRelaxedInsert = traits::relaxed_insert;
71 /// Group of \p extract_xxx functions does not require external locking
72 static CDS_CONSTEXPR const bool c_bExtractLockExternal = false;
74 # ifdef CDS_DOXYGEN_INVOKED
75 /// Returned pointer to \p mapped_type of extracted node
76 typedef cds::urcu::exempt_ptr< gc, T, T, disposer, void > exempt_ptr;
78 typedef cds::urcu::exempt_ptr< gc,
79 typename std::remove_pointer<mapped_type>::type,
80 typename std::remove_pointer<mapped_type>::type,
86 typedef typename gc::scoped_lock rcu_lock; ///< RCU scoped lock
90 typedef bronson_avltree::node< key_type, mapped_type, sync_monitor > node_type;
91 typedef typename node_type::version_type version_type;
93 typedef cds::details::Allocator< node_type, node_allocator_type > cxx_allocator;
94 typedef cds::urcu::details::check_deadlock_policy< gc, rcu_check_deadlock > check_deadlock_policy;
96 enum class find_result
113 result_inserted = allow_insert,
114 result_updated = allow_update,
121 nothing_required = -3,
122 rebalance_required = -2,
131 typedef typename sync_monitor::template scoped_lock<node_type> node_scoped_lock;
136 template <typename K>
137 static node_type * alloc_node( K&& key, int nHeight, version_type version, node_type * pParent, node_type * pLeft, node_type * pRight )
139 return cxx_allocator().New( std::forward<K>( key ), nHeight, version, pParent, pLeft, pRight );
142 static void free_node( node_type * pNode )
144 // Free node without disposer
145 assert( !pNode->is_valued( memory_model::memory_order_relaxed ));
146 assert( pNode->m_SyncMonitorInjection.check_free());
147 cxx_allocator().Delete( pNode );
150 static void free_value( mapped_type pVal )
155 static node_type * child( node_type * pNode, int nDir, atomics::memory_order order )
157 return pNode->child( nDir ).load( order );
160 static node_type * parent( node_type * pNode, atomics::memory_order order )
162 return pNode->m_pParent.load( order );
168 node_type * m_pRetiredList; ///< head of retired node list
169 mapped_type m_pRetiredValue; ///< value retired
173 : m_pRetiredList( nullptr )
174 , m_pRetiredValue( nullptr )
182 void dispose( node_type * pNode )
184 assert( !pNode->is_valued( memory_model::memory_order_relaxed ));
185 pNode->m_pNextRemoved = m_pRetiredList;
186 m_pRetiredList = pNode;
189 void dispose_value( mapped_type pVal )
191 assert( m_pRetiredValue == nullptr );
192 m_pRetiredValue = pVal;
196 struct internal_disposer
198 void operator()( node_type * p ) const
206 assert( !gc::is_locked() );
208 // TODO: use RCU::batch_retire
211 for ( node_type * p = m_pRetiredList; p; ) {
212 node_type * pNext = static_cast<node_type *>( p->m_pNextRemoved );
213 // Value already disposed
214 gc::template retire_ptr<internal_disposer>( p );
219 if ( m_pRetiredValue )
220 gc::template retire_ptr<disposer>( m_pRetiredValue );
228 typename node_type::base_class m_Root;
230 item_counter m_ItemCounter;
231 mutable sync_monitor m_Monitor;
236 /// Creates empty map
238 : m_pRoot( static_cast<node_type *>( &m_Root ))
249 The \p key_type should be constructible from a value of type \p K.
251 RCU \p synchronize() can be called. RCU should not be locked.
253 Returns \p true if inserting successful, \p false otherwise.
255 template <typename K>
256 bool insert( K const& key, mapped_type pVal )
258 return do_update(key, key_comparator(),
259 [pVal]( node_type * pNode ) -> mapped_type
261 assert( pNode->m_pValue.load( memory_model::memory_order_relaxed ) == nullptr );
265 update_flags::allow_insert
266 ) == update_flags::result_inserted;
269 /// Updates the value for \p key
271 The operation performs inserting or updating the value for \p key with lock-free manner.
272 If \p bInsert is \p false, only updating of existing node is possible.
274 If \p key is not found and inserting is allowed (i.e. \p bInsert is \p true),
275 then the new node created from \p key will be inserted into the map; note that in this case the \ref key_type should be
276 constructible from type \p K.
277 Otherwise, the value for \p key will be changed to \p pVal.
279 RCU \p synchronize() method can be called. RCU should not be locked.
281 Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successfull,
282 \p second is \p true if new node has been added or \p false if the node with \p key
285 template <typename K>
286 std::pair<bool, bool> update( K const& key, mapped_type pVal, bool bInsert = true )
288 int result = do_update( key, key_comparator(),
289 [pVal]( node_type * ) -> mapped_type
293 update_flags::allow_update | (bInsert ? update_flags::allow_insert : 0)
295 return std::make_pair( result != 0, (result & update_flags::result_inserted) != 0 );
299 template <typename K>
300 std::pair<bool, bool> ensure( K const& key, mapped_type pVal )
302 return update( key, pVal, true );
307 /// Delete \p key from the map
309 RCU \p synchronize() method can be called. RCU should not be locked.
311 Return \p true if \p key is found and deleted, \p false otherwise
313 template <typename K>
314 bool erase( K const& key )
319 []( key_type const&, mapped_type pVal, rcu_disposer& disp ) -> bool { disp.dispose_value( pVal ); return true; }
323 /// Deletes the item from the map using \p pred predicate for searching
325 The function is an analog of \p erase(K const&)
326 but \p pred is used for key comparing.
327 \p Less functor has the interface like \p std::less.
328 \p Less must imply the same element order as the comparator used for building the map.
330 template <typename K, typename Less>
331 bool erase_with( K const& key, Less pred )
336 cds::opt::details::make_comparator_from_less<Less>(),
337 []( key_type const&, mapped_type pVal, rcu_disposer& disp ) -> bool { disp.dispose_value( pVal ); return true; }
341 /// Delete \p key from the map
343 The function searches an item with key \p key, calls \p f functor
344 and deletes the item. If \p key is not found, the functor is not called.
346 The functor \p Func interface:
349 void operator()( key_type const& key, std::remove_pointer<mapped_type>::type& val) { ... }
353 RCU \p synchronize method can be called. RCU should not be locked.
355 Return \p true if key is found and deleted, \p false otherwise
357 template <typename K, typename Func>
358 bool erase( K const& key, Func f )
363 [&f]( key_type const& key, mapped_type pVal, rcu_disposer& disp ) -> bool {
366 disp.dispose_value(pVal);
372 /// Deletes the item from the map using \p pred predicate for searching
374 The function is an analog of \p erase(K const&, Func)
375 but \p pred is used for key comparing.
376 \p Less functor has the interface like \p std::less.
377 \p Less must imply the same element order as the comparator used for building the map.
379 template <typename K, typename Less, typename Func>
380 bool erase_with( K const& key, Less pred, Func f )
385 cds::opt::details::make_comparator_from_less<Less>(),
386 [&f]( key_type const& key, mapped_type pVal, rcu_disposer& disp ) -> bool {
389 disp.dispose_value(pVal);
395 /// Extracts a value with minimal key from the map
397 Returns \p exempt_ptr to the leftmost item.
398 If the tree is empty, returns empty \p exempt_ptr.
400 Note that the function returns only the value for minimal key.
401 To retrieve its key use \p extract_min( Func ) member function.
403 @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
404 It means that the function gets leftmost leaf of the tree and tries to unlink it.
405 During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
406 So, the function returns the item with minimum key at the moment of tree traversing.
408 RCU \p synchronize method can be called. RCU should NOT be locked.
409 The function does not free the item.
410 The deallocator will be implicitly invoked when the returned object is destroyed or when
411 its \p release() member function is called.
413 exempt_ptr extract_min()
415 return exempt_ptr(do_extract_min( []( key_type const& ) {}));
418 /// Extracts minimal key key and corresponding value
420 Returns \p exempt_ptr to the leftmost item.
421 If the tree is empty, returns empty \p exempt_ptr.
423 \p Func functor is used to store minimal key.
424 \p Func has the following signature:
427 void operator()( key_type const& key );
430 If the tree is empty, \p f is not called.
431 Otherwise, is it called with minimal key, the pointer to corresponding value is returned
434 @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
435 It means that the function gets leftmost leaf of the tree and tries to unlink it.
436 During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
437 So, the function returns the item with minimum key at the moment of tree traversing.
439 RCU \p synchronize method can be called. RCU should NOT be locked.
440 The function does not free the item.
441 The deallocator will be implicitly invoked when the returned object is destroyed or when
442 its \p release() member function is called.
444 template <typename Func>
445 exempt_ptr extract_min( Func f )
447 return exempt_ptr(do_extract_min( [&f]( key_type const& key ) { f(key); }));
450 /// Extracts minimal key key and corresponding value
452 This function is a shortcut for the following call:
455 exempt_ptr xp = theTree.extract_min( [&key]( key_type const& k ) { key = k; } );
457 \p key_type should be copy-assignable. The copy of minimal key
458 is returned in \p min_key argument.
460 typename std::enable_if< std::is_copy_assignable<key_type>::value, exempt_ptr >::type
461 extract_min_key( key_type& min_key )
463 return exempt_ptr(do_extract_min( [&min_key]( key_type const& key ) { min_key = key; }));
466 /// Extracts a value with maximal key from the tree
468 Returns \p exempt_ptr pointer to the rightmost item.
469 If the set is empty, returns empty \p exempt_ptr.
471 Note that the function returns only the value for maximal key.
472 To retrieve its key use \p extract_max( Func ) member function.
474 @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
475 It means that the function gets rightmost leaf of the tree and tries to unlink it.
476 During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
477 So, the function returns the item with maximum key at the moment of tree traversing.
479 RCU \p synchronize method can be called. RCU should NOT be locked.
480 The function does not free the item.
481 The deallocator will be implicitly invoked when the returned object is destroyed or when
482 its \p release() is called.
484 exempt_ptr extract_max()
486 return exempt_ptr(do_extract_max( []( key_type const& ) {}));
489 /// Extracts the maximal key and corresponding value
491 Returns \p exempt_ptr pointer to the rightmost item.
492 If the set is empty, returns empty \p exempt_ptr.
494 \p Func functor is used to store maximal key.
495 \p Func has the following signature:
498 void operator()( key_type const& key );
501 If the tree is empty, \p f is not called.
502 Otherwise, is it called with maximal key, the pointer to corresponding value is returned
505 @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
506 It means that the function gets rightmost leaf of the tree and tries to unlink it.
507 During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
508 So, the function returns the item with maximum key at the moment of tree traversing.
510 RCU \p synchronize method can be called. RCU should NOT be locked.
511 The function does not free the item.
512 The deallocator will be implicitly invoked when the returned object is destroyed or when
513 its \p release() is called.
515 template <typename Func>
516 exempt_ptr extract_max( Func f )
518 return exempt_ptr(do_extract_max( [&f]( key_type const& key ) { f(key); }));
521 /// Extracts the maximal key and corresponding value
523 This function is a shortcut for the following call:
526 exempt_ptr xp = theTree.extract_max( [&key]( key_type const& k ) { key = k; } );
528 \p key_type should be copy-assignable. The copy of maximal key
529 is returned in \p max_key argument.
531 typename std::enable_if< std::is_copy_assignable<key_type>::value, exempt_ptr >::type
532 extract_max_key( key_type& max_key )
534 return exempt_ptr(do_extract_max( [&max_key]( key_type const& key ) { max_key = key; }));
537 /// Extracts an item from the map
539 The function searches an item with key equal to \p key in the tree,
540 unlinks it, and returns \p exempt_ptr pointer to a value found.
541 If \p key is not found the function returns an empty \p exempt_ptr.
543 RCU \p synchronize method can be called. RCU should NOT be locked.
544 The function does not destroy the value found.
545 The disposer will be implicitly invoked when the returned object is destroyed or when
546 its \p release() member function is called.
548 template <typename Q>
549 exempt_ptr extract( Q const& key )
551 return exempt_ptr(do_extract( key ));
555 /// Extracts an item from the map using \p pred for searching
557 The function is an analog of \p extract(Q const&)
558 but \p pred is used for key compare.
559 \p Less has the interface like \p std::less.
560 \p pred must imply the same element order as the comparator used for building the tree.
562 template <typename Q, typename Less>
563 exempt_ptr extract_with( Q const& key, Less pred )
565 return exempt_ptr(do_extract_with( key, pred ));
568 /// Find the key \p key
570 The function searches the item with key equal to \p key and calls the functor \p f for item found.
571 The interface of \p Func functor is:
574 void operator()( key_type const& key, mapped_type& item );
577 where \p item is the item found.
578 The functor is called under node-level lock.
580 The function applies RCU lock internally.
582 The function returns \p true if \p key is found, \p false otherwise.
584 template <typename K, typename Func>
585 bool find( K const& key, Func f )
587 return do_find( key, key_comparator(),
588 [&f]( node_type * pNode ) -> bool {
589 assert( pNode != nullptr );
590 mapped_type pVal = pNode->m_pValue.load( memory_model::memory_order_relaxed );
592 f( pNode->m_key, *pVal );
600 /// Finds the key \p val using \p pred predicate for searching
602 The function is an analog of \p find(K const&, Func)
603 but \p pred is used for key comparing.
604 \p Less functor has the interface like \p std::less.
605 \p Less must imply the same element order as the comparator used for building the map.
607 template <typename K, typename Less, typename Func>
608 bool find_with( K const& key, Less pred, Func f )
611 return do_find( key, cds::opt::details::make_comparator_from_less<Less>(),
612 [&f]( node_type * pNode ) -> bool {
613 assert( pNode != nullptr );
614 mapped_type pVal = pNode->m_pValue.load( memory_model::memory_order_relaxed );
616 f( pNode->m_key, *pVal );
624 /// Find the key \p key
626 The function searches the item with key equal to \p key
627 and returns \p true if it is found, and \p false otherwise.
629 The function applies RCU lock internally.
631 template <typename K>
632 bool find( K const& key )
634 return do_find( key, key_comparator(), []( node_type * ) -> bool { return true; });
637 /// Finds the key \p val using \p pred predicate for searching
639 The function is an analog of \p find(K const&)
640 but \p pred is used for key comparing.
641 \p Less functor has the interface like \p std::less.
642 \p Less must imply the same element order as the comparator used for building the map.
644 template <typename K, typename Less>
645 bool find_with( K const& key, Less pred )
648 return do_find( key, cds::opt::details::make_comparator_from_less<Less>(), []( node_type * ) -> bool { return true; } );
651 /// Clears the tree (thread safe, not atomic)
653 The function unlink all items from the tree.
654 The function is thread safe but not atomic: in multi-threaded environment with parallel insertions
658 assert( set.empty() );
660 the assertion could be raised.
662 For each node the \ref disposer will be called after unlinking.
664 RCU \p synchronize method can be called. RCU should not be locked.
668 while ( extract_min() );
671 /// Clears the tree (not thread safe)
673 This function is not thread safe and may be called only when no other thread deals with the tree.
674 The function is used in the tree destructor.
678 clear(); // temp solution
682 /// Checks if the map is empty
685 return m_Root.m_pRight.load( memory_model::memory_order_relaxed ) == nullptr;
688 /// Returns item count in the map
690 Only leaf nodes containing user data are counted.
692 The value returned depends on item counter type provided by \p Traits template parameter.
693 If it is \p atomicity::empty_item_counter this function always returns 0.
695 The function is not suitable for checking the tree emptiness, use \p empty()
696 member function for this purpose.
700 return m_ItemCounter;
703 /// Returns const reference to internal statistics
704 stat const& statistics() const
709 /// Returns reference to \p sync_monitor object
710 sync_monitor& monitor()
715 sync_monitor const& monitor() const
721 /// Checks internal consistency (not atomic, not thread-safe)
723 The debugging function to check internal consistency of the tree.
725 bool check_consistency() const
727 return check_consistency([]( size_t /*nLevel*/, size_t /*hLeft*/, size_t /*hRight*/ ){} );
730 /// Checks internal consistency (not atomic, not thread-safe)
732 The debugging function to check internal consistency of the tree.
733 The functor \p Func is called if a violation of internal tree structure
737 void operator()( size_t nLevel, size_t hLeft, size_t hRight );
741 - \p nLevel - the level where the violation is found
742 - \p hLeft - the height of left subtree
743 - \p hRight - the height of right subtree
745 The functor is called for each violation found.
747 template <typename Func>
748 bool check_consistency( Func f ) const
750 node_type * pChild = child( m_pRoot, right_child, memory_model::memory_order_relaxed );
753 do_check_consistency( pChild, 1, f, nErrors );
761 template <typename Func>
762 size_t do_check_consistency( node_type * pNode, size_t nLevel, Func f, size_t& nErrors ) const
766 node_type * pLeft = child( pNode, left_child, memory_model::memory_order_relaxed );
767 node_type * pRight = child( pNode, right_child, memory_model::memory_order_relaxed );
768 if ( pLeft && cmp( pLeft->m_key, pNode->m_key ) > 0 )
770 if ( pRight && cmp( pNode->m_key, pRight->m_key ) > 0 )
773 size_t hLeft = do_check_consistency( pLeft, nLevel + 1, f, nErrors );
774 size_t hRight = do_check_consistency( pRight, nLevel + 1, f, nErrors );
776 if ( hLeft >= hRight ) {
777 if ( hLeft - hRight > 1 ) {
778 f( nLevel, hLeft, hRight );
784 if ( hRight - hLeft > 1 ) {
785 f( nLevel, hLeft, hRight );
794 template <typename Q, typename Compare, typename Func>
795 bool do_find( Q& key, Compare cmp, Func f ) const
800 result = try_find( key, cmp, f, m_pRoot, 1, 0 );
802 assert( result != find_result::retry );
803 return result == find_result::found;
806 template <typename K, typename Compare, typename Func>
807 int do_update( K const& key, Compare cmp, Func funcUpdate, int nFlags )
809 check_deadlock_policy::check();
811 rcu_disposer removed_list;
814 return try_update_root( key, cmp, nFlags, funcUpdate, removed_list );
818 template <typename K, typename Compare, typename Func>
819 bool do_remove( K const& key, Compare cmp, Func func )
821 // Func must return true if the value was disposed
822 // or false if the value was extracted
824 check_deadlock_policy::check();
826 rcu_disposer removed_list;
829 return try_remove_root( key, cmp, func, removed_list );
833 template <typename Func>
834 mapped_type do_extract_min( Func f )
836 mapped_type pExtracted = nullptr;
839 [&pExtracted, &f]( key_type const& key, mapped_type pVal, rcu_disposer& ) -> bool { f( key ); pExtracted = pVal; return false; }
844 template <typename Func>
845 mapped_type do_extract_max( Func f )
847 mapped_type pExtracted = nullptr;
850 [&pExtracted, &f]( key_type const& key, mapped_type pVal, rcu_disposer& ) -> bool { f( key ); pExtracted = pVal; return false; }
855 template <typename Func>
856 void do_extract_minmax( int nDir, Func func )
858 check_deadlock_policy::check();
860 rcu_disposer removed_list;
864 int result = update_flags::failed;
866 // get right child of root
867 node_type * pChild = child( m_pRoot, right_child, memory_model::memory_order_acquire );
869 version_type nChildVersion = pChild->version( memory_model::memory_order_relaxed );
870 if ( nChildVersion & node_type::shrinking ) {
871 m_stat.onRemoveRootWaitShrinking();
872 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
873 result = update_flags::retry;
875 else if ( pChild == child( m_pRoot, right_child, memory_model::memory_order_acquire )) {
876 result = try_extract_minmax( nDir, func, m_pRoot, pChild, nChildVersion, removed_list );
879 } while ( result == update_flags::retry );
883 template <typename Q>
884 mapped_type do_extract( Q const& key )
886 mapped_type pExtracted = nullptr;
890 [&pExtracted]( key_type const&, mapped_type pVal, rcu_disposer& ) -> bool { pExtracted = pVal; return false; }
895 template <typename Q, typename Less>
896 mapped_type do_extract_with( Q const& key, Less pred )
899 mapped_type pExtracted = nullptr;
902 cds::opt::details::make_comparator_from_less<Less>(),
903 [&pExtracted]( key_type const&, mapped_type pVal, rcu_disposer& ) -> bool { pExtracted = pVal; return false; }
912 template <typename Q, typename Compare, typename Func>
913 find_result try_find( Q const& key, Compare cmp, Func f, node_type * pNode, int nDir, version_type nVersion ) const
915 assert( gc::is_locked() );
919 node_type * pChild = child( pNode, nDir, memory_model::memory_order_relaxed );
921 if ( pNode->version( memory_model::memory_order_acquire ) != nVersion ) {
922 m_stat.onFindRetry();
923 return find_result::retry;
926 m_stat.onFindFailed();
927 return find_result::not_found;
930 int nCmp = cmp( key, pChild->m_key );
932 if ( pChild->is_valued( memory_model::memory_order_relaxed ) ) {
934 node_scoped_lock l( m_Monitor, *pChild );
935 if ( pChild->is_valued( memory_model::memory_order_relaxed )) {
937 m_stat.onFindSuccess();
938 return find_result::found;
943 m_stat.onFindFailed();
944 return find_result::not_found;
947 version_type nChildVersion = pChild->version( memory_model::memory_order_acquire );
948 if ( nChildVersion & node_type::shrinking ) {
949 m_stat.onFindWaitShrinking();
950 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
952 if ( pNode->version( memory_model::memory_order_acquire ) != nVersion ) {
953 m_stat.onFindRetry();
954 return find_result::retry;
957 else if ( nChildVersion != node_type::unlinked ) {
958 if ( pNode->version( memory_model::memory_order_acquire ) != nVersion ) {
959 m_stat.onFindRetry();
960 return find_result::retry;
963 find_result found = try_find( key, cmp, f, pChild, nCmp, nChildVersion );
964 if ( found != find_result::retry )
968 if ( pNode->version( memory_model::memory_order_acquire ) != nVersion ) {
969 m_stat.onFindRetry();
970 return find_result::retry;
975 template <typename K, typename Compare, typename Func>
976 int try_update_root( K const& key, Compare cmp, int nFlags, Func funcUpdate, rcu_disposer& disp )
978 assert( gc::is_locked() );
982 // get right child of root
983 node_type * pChild = child( m_pRoot, right_child, memory_model::memory_order_acquire );
985 version_type nChildVersion = pChild->version( memory_model::memory_order_relaxed );
986 if ( nChildVersion & node_type::shrinking ) {
987 m_stat.onUpdateRootWaitShrinking();
988 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
989 result = update_flags::retry;
991 else if ( pChild == child( m_pRoot, right_child, memory_model::memory_order_acquire )) {
992 result = try_update( key, cmp, nFlags, funcUpdate, m_pRoot, pChild, nChildVersion, disp );
995 result = update_flags::retry;
999 if ( nFlags & update_flags::allow_insert ) {
1000 // insert into tree as right child of the root
1002 node_scoped_lock l( m_Monitor, *m_pRoot );
1003 if ( child( m_pRoot, right_child, memory_model::memory_order_acquire ) != nullptr ) {
1004 result = update_flags::retry;
1008 node_type * pNew = alloc_node( key, 1, 0, m_pRoot, nullptr, nullptr );
1009 mapped_type pVal = funcUpdate( pNew );
1010 assert( pVal != nullptr );
1011 pNew->m_pValue.store( pVal, memory_model::memory_order_release );
1013 m_pRoot->child( pNew, right_child, memory_model::memory_order_relaxed );
1014 m_pRoot->height( 2, memory_model::memory_order_relaxed );
1018 m_stat.onInsertSuccess();
1019 return update_flags::result_inserted;
1022 return update_flags::failed;
1024 } while ( result == update_flags::retry );
1028 template <typename K, typename Compare, typename Func>
1029 bool try_remove_root( K const& key, Compare cmp, Func func, rcu_disposer& disp )
1031 assert( gc::is_locked() );
1035 // get right child of root
1036 node_type * pChild = child( m_pRoot, right_child, memory_model::memory_order_acquire );
1038 version_type nChildVersion = pChild->version( memory_model::memory_order_relaxed );
1039 if ( nChildVersion & node_type::shrinking ) {
1040 m_stat.onRemoveRootWaitShrinking();
1041 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
1042 result = update_flags::retry;
1044 else if ( pChild == child( m_pRoot, right_child, memory_model::memory_order_acquire )) {
1045 result = try_remove( key, cmp, func, m_pRoot, pChild, nChildVersion, disp );
1048 result = update_flags::retry;
1052 } while ( result == update_flags::retry );
1054 return result == update_flags::result_removed;
1057 template <typename K, typename Compare, typename Func>
1058 int try_update( K const& key, Compare cmp, int nFlags, Func funcUpdate, node_type * pParent, node_type * pNode, version_type nVersion, rcu_disposer& disp )
1060 assert( gc::is_locked() );
1061 assert( nVersion != node_type::unlinked );
1062 CDS_UNUSED( pParent );
1064 int nCmp = cmp( key, pNode->m_key );
1066 if ( nFlags & update_flags::allow_update ) {
1067 return try_update_node( funcUpdate, pNode, disp );
1069 return update_flags::failed;
1074 node_type * pChild = child( pNode, nCmp, memory_model::memory_order_relaxed );
1075 if ( pNode->version(memory_model::memory_order_acquire) != nVersion ) {
1076 m_stat.onUpdateRetry();
1077 return update_flags::retry;
1080 if ( pChild == nullptr ) {
1082 if ( nFlags & update_flags::allow_insert )
1083 result = try_insert_node( key, funcUpdate, pNode, nCmp, nVersion, disp );
1085 result = update_flags::failed;
1089 result = update_flags::retry;
1090 version_type nChildVersion = pChild->version( memory_model::memory_order_acquire );
1091 if ( nChildVersion & node_type::shrinking ) {
1092 m_stat.onUpdateWaitShrinking();
1093 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
1096 else if ( pChild == child( pNode, nCmp, memory_model::memory_order_relaxed )) {
1097 // this second read is important, because it is protected by nChildVersion
1099 // validate the read that our caller took to get to node
1100 if ( pNode->version( memory_model::memory_order_relaxed ) != nVersion ) {
1101 m_stat.onUpdateRetry();
1102 return update_flags::retry;
1105 // At this point we know that the traversal our parent took to get to node is still valid.
1106 // The recursive implementation will validate the traversal from node to
1107 // child, so just prior to the node nVersion validation both traversals were definitely okay.
1108 // This means that we are no longer vulnerable to node shrinks, and we don't need
1109 // to validate node version any more.
1110 result = try_update( key, cmp, nFlags, funcUpdate, pNode, pChild, nChildVersion, disp );
1114 if ( result == update_flags::retry && pNode->version( memory_model::memory_order_relaxed ) != nVersion ) {
1115 m_stat.onUpdateRetry();
1116 return update_flags::retry;
1118 } while ( result == update_flags::retry );
1122 template <typename K, typename Compare, typename Func>
1123 int try_remove( K const& key, Compare cmp, Func func, node_type * pParent, node_type * pNode, version_type nVersion, rcu_disposer& disp )
1125 assert( gc::is_locked() );
1126 assert( nVersion != node_type::unlinked );
1128 int nCmp = cmp( key, pNode->m_key );
1130 return try_remove_node( pParent, pNode, nVersion, func, disp );
1134 node_type * pChild = child( pNode, nCmp, memory_model::memory_order_relaxed );
1135 if ( pNode->version(memory_model::memory_order_acquire) != nVersion ) {
1136 m_stat.onRemoveRetry();
1137 return update_flags::retry;
1140 if ( pChild == nullptr ) {
1141 return update_flags::failed;
1145 result = update_flags::retry;
1146 version_type nChildVersion = pChild->version( memory_model::memory_order_acquire );
1147 if ( nChildVersion & node_type::shrinking ) {
1148 m_stat.onRemoveWaitShrinking();
1149 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
1152 else if ( pChild == child( pNode, nCmp, memory_model::memory_order_relaxed )) {
1153 // this second read is important, because it is protected by nChildVersion
1155 // validate the read that our caller took to get to node
1156 if ( pNode->version( memory_model::memory_order_relaxed ) != nVersion ) {
1157 m_stat.onRemoveRetry();
1158 return update_flags::retry;
1161 // At this point we know that the traversal our parent took to get to node is still valid.
1162 // The recursive implementation will validate the traversal from node to
1163 // child, so just prior to the node nVersion validation both traversals were definitely okay.
1164 // This means that we are no longer vulnerable to node shrinks, and we don't need
1165 // to validate node version any more.
1166 result = try_remove( key, cmp, func, pNode, pChild, nChildVersion, disp );
1170 if ( result == update_flags::retry && pNode->version( memory_model::memory_order_relaxed ) != nVersion ) {
1171 m_stat.onRemoveRetry();
1172 return update_flags::retry;
1174 } while ( result == update_flags::retry );
1178 template <typename Func>
1179 int try_extract_minmax( int nDir, Func func, node_type * pParent, node_type * pNode, version_type nVersion, rcu_disposer& disp )
1181 assert( gc::is_locked() );
1182 assert( nVersion != node_type::unlinked );
1186 node_type * pChild = child( pNode, nDir, memory_model::memory_order_relaxed );
1187 if ( pNode->version(memory_model::memory_order_acquire) != nVersion ) {
1188 m_stat.onRemoveRetry();
1189 return update_flags::retry;
1192 if ( pChild == nullptr ) {
1194 return try_remove_node( pParent, pNode, nVersion, func, disp );
1197 result = update_flags::retry;
1198 version_type nChildVersion = pChild->version( memory_model::memory_order_acquire );
1199 if ( nChildVersion & node_type::shrinking ) {
1200 m_stat.onRemoveWaitShrinking();
1201 pChild->template wait_until_shrink_completed<back_off>( memory_model::memory_order_relaxed );
1204 else if ( pChild == child( pNode, nDir, memory_model::memory_order_relaxed )) {
1205 // this second read is important, because it is protected by nChildVersion
1207 // validate the read that our caller took to get to node
1208 if ( pNode->version( memory_model::memory_order_relaxed ) != nVersion ) {
1209 m_stat.onRemoveRetry();
1210 return update_flags::retry;
1213 // At this point we know that the traversal our parent took to get to node is still valid.
1214 // The recursive implementation will validate the traversal from node to
1215 // child, so just prior to the node nVersion validation both traversals were definitely okay.
1216 // This means that we are no longer vulnerable to node shrinks, and we don't need
1217 // to validate node version any more.
1218 result = try_extract_minmax( nDir, func, pNode, pChild, nChildVersion, disp );
1222 if ( result == update_flags::retry && pNode->version( memory_model::memory_order_relaxed ) != nVersion ) {
1223 m_stat.onRemoveRetry();
1224 return update_flags::retry;
1226 } while ( result == update_flags::retry );
1230 template <typename K, typename Func>
1231 int try_insert_node( K const& key, Func funcUpdate, node_type * pNode, int nDir, version_type nVersion, rcu_disposer& disp )
1235 auto fnCreateNode = [&funcUpdate]( node_type * pNew ) {
1236 mapped_type pVal = funcUpdate( pNew );
1237 assert( pVal != nullptr );
1238 pNew->m_pValue.store( pVal, memory_model::memory_order_relaxed );
1241 if ( c_bRelaxedInsert ) {
1242 if ( pNode->version( memory_model::memory_order_acquire ) != nVersion
1243 || child( pNode, nDir, memory_model::memory_order_relaxed ) != nullptr )
1245 m_stat.onInsertRetry();
1246 return update_flags::retry;
1249 fnCreateNode( pNew = alloc_node( key, 1, 0, pNode, nullptr, nullptr ));
1252 node_type * pDamaged;
1254 assert( pNode != nullptr );
1255 node_scoped_lock l( m_Monitor, *pNode );
1257 if ( pNode->version( memory_model::memory_order_relaxed ) != nVersion
1258 || child( pNode, nDir, memory_model::memory_order_relaxed ) != nullptr )
1260 if ( c_bRelaxedInsert ) {
1261 mapped_type pVal = pNew->m_pValue.load( memory_model::memory_order_relaxed );
1262 pNew->m_pValue.store( nullptr, memory_model::memory_order_relaxed );
1265 m_stat.onRelaxedInsertFailed();
1268 m_stat.onInsertRetry();
1269 return update_flags::retry;
1272 if ( !c_bRelaxedInsert )
1273 fnCreateNode( pNew = alloc_node( key, 1, 0, pNode, nullptr, nullptr ));
1275 pNode->child( pNew, nDir, memory_model::memory_order_relaxed );
1276 pDamaged = fix_height_locked( pNode );
1280 m_stat.onInsertSuccess();
1283 fix_height_and_rebalance( pDamaged, disp );
1284 m_stat.onInsertRebalanceRequired();
1287 return update_flags::result_inserted;
1290 template <typename Func>
1291 int try_update_node( Func funcUpdate, node_type * pNode, rcu_disposer& disp )
1294 assert( pNode != nullptr );
1296 node_scoped_lock l( m_Monitor, *pNode );
1298 if ( pNode->is_unlinked( memory_model::memory_order_relaxed )) {
1299 m_stat.onUpdateUnlinked();
1300 return update_flags::retry;
1303 pOld = pNode->value( memory_model::memory_order_relaxed );
1304 mapped_type pVal = funcUpdate( pNode );
1308 assert( pVal != nullptr );
1309 pNode->m_pValue.store( pVal, memory_model::memory_order_relaxed );
1314 disp.dispose_value(pOld);
1315 m_stat.onDisposeValue();
1318 m_stat.onUpdateSuccess();
1319 return update_flags::result_updated;
1322 template <typename Func>
1323 int try_remove_node( node_type * pParent, node_type * pNode, version_type nVersion, Func func, rcu_disposer& disp )
1325 assert( pParent != nullptr );
1326 assert( pNode != nullptr );
1328 if ( !pNode->is_valued( atomics::memory_order_relaxed ) )
1329 return update_flags::failed;
1331 if ( child( pNode, left_child, memory_model::memory_order_relaxed ) == nullptr
1332 || child( pNode, right_child, memory_model::memory_order_relaxed ) == nullptr )
1334 node_type * pDamaged;
1337 node_scoped_lock lp( m_Monitor, *pParent );
1338 if ( pParent->is_unlinked( atomics::memory_order_relaxed ) || parent( pNode, memory_model::memory_order_relaxed ) != pParent )
1339 return update_flags::retry;
1342 node_scoped_lock ln( m_Monitor, *pNode );
1343 pOld = pNode->value( memory_model::memory_order_relaxed );
1344 if ( !( pNode->version( memory_model::memory_order_relaxed ) == nVersion
1346 && try_unlink_locked( pParent, pNode, disp )))
1348 return update_flags::retry;
1351 pDamaged = fix_height_locked( pParent );
1355 if ( func( pNode->m_key, pOld, disp )) // calls pOld disposer inside
1356 m_stat.onDisposeValue();
1358 m_stat.onExtractValue();
1361 fix_height_and_rebalance( pDamaged, disp );
1362 m_stat.onRemoveRebalanceRequired();
1364 return update_flags::result_removed;
1367 int result = update_flags::retry;
1370 node_scoped_lock ln( m_Monitor, *pNode );
1371 pOld = pNode->value( atomics::memory_order_relaxed );
1372 if ( pNode->version( atomics::memory_order_relaxed ) == nVersion && pOld ) {
1373 pNode->m_pValue.store( nullptr, atomics::memory_order_relaxed );
1374 result = update_flags::result_removed;
1378 if ( result == update_flags::result_removed ) {
1380 if ( func( pNode->m_key, pOld, disp )) // calls pOld disposer inside
1381 m_stat.onDisposeValue();
1383 m_stat.onExtractValue();
1390 bool try_unlink_locked( node_type * pParent, node_type * pNode, rcu_disposer& disp )
1392 // pParent and pNode must be locked
1393 assert( !pParent->is_unlinked(memory_model::memory_order_relaxed) );
1395 node_type * pParentLeft = child( pParent, left_child, memory_model::memory_order_relaxed );
1396 node_type * pParentRight = child( pParent, right_child, memory_model::memory_order_relaxed );
1397 if ( pNode != pParentLeft && pNode != pParentRight ) {
1398 // node is no longer a child of parent
1402 assert( !pNode->is_unlinked( memory_model::memory_order_relaxed ) );
1403 assert( pParent == parent( pNode, memory_model::memory_order_relaxed));
1405 node_type * pLeft = child( pNode, left_child, memory_model::memory_order_relaxed );
1406 node_type * pRight = child( pNode, right_child, memory_model::memory_order_relaxed );
1407 if ( pLeft != nullptr && pRight != nullptr ) {
1408 // splicing is no longer possible
1411 node_type * pSplice = pLeft ? pLeft : pRight;
1413 if ( pParentLeft == pNode )
1414 pParent->m_pLeft.store( pSplice, memory_model::memory_order_relaxed );
1416 pParent->m_pRight.store( pSplice, memory_model::memory_order_relaxed );
1419 pSplice->m_pParent.store( pParent, memory_model::memory_order_release );
1421 // Mark the node as unlinked
1422 pNode->version( node_type::unlinked, memory_model::memory_order_release );
1424 // The value will be disposed by calling function
1425 pNode->m_pValue.store( nullptr, memory_model::memory_order_relaxed );
1427 disp.dispose( pNode );
1428 m_stat.onDisposeNode();
1435 private: // rotations
1437 int estimate_node_condition( node_type * pNode )
1439 node_type * pLeft = child( pNode, left_child, memory_model::memory_order_relaxed );
1440 node_type * pRight = child( pNode, right_child, memory_model::memory_order_relaxed );
1442 if ( (pLeft == nullptr || pRight == nullptr) && !pNode->is_valued( memory_model::memory_order_relaxed ))
1443 return unlink_required;
1445 int h = pNode->height( memory_model::memory_order_relaxed );
1446 int hL = pLeft ? pLeft->height( memory_model::memory_order_relaxed ) : 0;
1447 int hR = pRight ? pRight->height( memory_model::memory_order_relaxed ) : 0;
1449 int hNew = 1 + std::max( hL, hR );
1450 int nBalance = hL - hR;
1452 if ( nBalance < -1 || nBalance > 1 )
1453 return rebalance_required;
1455 return h != hNew ? hNew : nothing_required;
1458 node_type * fix_height( node_type * pNode )
1460 assert( pNode != nullptr );
1461 node_scoped_lock l( m_Monitor, *pNode );
1462 return fix_height_locked( pNode );
1465 node_type * fix_height_locked( node_type * pNode )
1467 // pNode must be locked!!!
1468 int h = estimate_node_condition( pNode );
1470 case rebalance_required:
1471 case unlink_required:
1473 case nothing_required:
1476 pNode->height( h, memory_model::memory_order_relaxed );
1477 return parent( pNode, memory_model::memory_order_relaxed );
1481 void fix_height_and_rebalance( node_type * pNode, rcu_disposer& disp )
1483 while ( pNode && parent( pNode, memory_model::memory_order_relaxed )) {
1484 int nCond = estimate_node_condition( pNode );
1485 if ( nCond == nothing_required || pNode->is_unlinked( memory_model::memory_order_relaxed ) )
1488 if ( nCond != unlink_required && nCond != rebalance_required )
1489 pNode = fix_height( pNode );
1491 node_type * pParent = parent( pNode, memory_model::memory_order_relaxed );
1492 assert( pParent != nullptr );
1494 node_scoped_lock lp( m_Monitor, *pParent );
1495 if ( !pParent->is_unlinked( memory_model::memory_order_relaxed )
1496 && parent( pNode, memory_model::memory_order_relaxed ) == pParent )
1498 node_scoped_lock ln( m_Monitor, *pNode );
1499 pNode = rebalance_locked( pParent, pNode, disp );
1506 node_type * rebalance_locked( node_type * pParent, node_type * pNode, rcu_disposer& disp )
1508 // pParent and pNode should be locked.
1509 // Returns a damaged node, or nullptr if no more rebalancing is necessary
1510 assert( parent( pNode, memory_model::memory_order_relaxed ) == pParent );
1512 node_type * pLeft = child( pNode, left_child, memory_model::memory_order_relaxed );
1513 node_type * pRight = child( pNode, right_child, memory_model::memory_order_relaxed );
1515 if ( (pLeft == nullptr || pRight == nullptr) && !pNode->is_valued( memory_model::memory_order_relaxed )) {
1516 if ( try_unlink_locked( pParent, pNode, disp ))
1517 return fix_height_locked( pParent );
1519 // retry needed for pNode
1524 assert( child( pParent, left_child, memory_model::memory_order_relaxed ) == pNode
1525 || child( pParent, right_child, memory_model::memory_order_relaxed ) == pNode );
1527 int h = pNode->height( memory_model::memory_order_relaxed );
1528 int hL = pLeft ? pLeft->height( memory_model::memory_order_relaxed ) : 0;
1529 int hR = pRight ? pRight->height( memory_model::memory_order_relaxed ) : 0;
1530 int hNew = 1 + std::max( hL, hR );
1531 int balance = hL - hR;
1534 return rebalance_to_right_locked( pParent, pNode, pLeft, hR );
1535 else if ( balance < -1 )
1536 return rebalance_to_left_locked( pParent, pNode, pRight, hL );
1537 else if ( hNew != h ) {
1538 pNode->height( hNew, memory_model::memory_order_relaxed );
1540 // pParent is already locked
1541 return fix_height_locked( pParent );
1547 node_type * rebalance_to_right_locked( node_type * pParent, node_type * pNode, node_type * pLeft, int hR )
1549 assert( parent( pNode, memory_model::memory_order_relaxed ) == pParent );
1550 assert( child( pParent, left_child, memory_model::memory_order_relaxed ) == pNode
1551 || child( pParent, right_child, memory_model::memory_order_relaxed ) == pNode );
1553 // pParent and pNode is locked yet
1554 // pNode->pLeft is too large, we will rotate-right.
1555 // If pLeft->pRight is taller than pLeft->pLeft, then we will first rotate-left pLeft.
1558 assert( pLeft != nullptr );
1559 node_scoped_lock l( m_Monitor, *pLeft );
1560 if ( pNode->m_pLeft.load( memory_model::memory_order_relaxed ) != pLeft )
1561 return pNode; // retry for pNode
1563 int hL = pLeft->height( memory_model::memory_order_relaxed );
1565 return pNode; // retry
1567 node_type * pLRight = child( pLeft, right_child, memory_model::memory_order_relaxed );
1568 int hLR = pLRight ? pLRight->height( memory_model::memory_order_relaxed ) : 0;
1569 node_type * pLLeft = child( pLeft, left_child, memory_model::memory_order_relaxed );
1570 int hLL = pLLeft ? pLLeft->height( memory_model::memory_order_relaxed ) : 0;
1574 return rotate_right_locked( pParent, pNode, pLeft, hR, hLL, pLRight, hLR );
1577 assert( pLRight != nullptr );
1579 node_scoped_lock lr( m_Monitor, *pLRight );
1580 if ( pLeft->m_pRight.load( memory_model::memory_order_relaxed ) != pLRight )
1581 return pNode; // retry
1583 hLR = pLRight->height( memory_model::memory_order_relaxed );
1585 return rotate_right_locked( pParent, pNode, pLeft, hR, hLL, pLRight, hLR );
1587 node_type * pLRLeft = child( pLRight, left_child, memory_model::memory_order_relaxed );
1588 int hLRL = pLRLeft ? pLRLeft->height( memory_model::memory_order_relaxed ) : 0;
1589 int balance = hLL - hLRL;
1590 if ( balance >= -1 && balance <= 1 && !((hLL == 0 || hLRL == 0) && !pLeft->is_valued(memory_model::memory_order_relaxed))) {
1591 // nParent.child.left won't be damaged after a double rotation
1592 return rotate_right_over_left_locked( pParent, pNode, pLeft, hR, hLL, pLRight, hLRL );
1596 // focus on pLeft, if necessary pNode will be balanced later
1597 return rebalance_to_left_locked( pNode, pLeft, pLRight, hLL );
1602 node_type * rebalance_to_left_locked( node_type * pParent, node_type * pNode, node_type * pRight, int hL )
1604 assert( parent( pNode, memory_model::memory_order_relaxed ) == pParent );
1605 assert( child( pParent, left_child, memory_model::memory_order_relaxed ) == pNode
1606 || child( pParent, right_child, memory_model::memory_order_relaxed ) == pNode );
1608 // pParent and pNode is locked yet
1610 assert( pRight != nullptr );
1611 node_scoped_lock l( m_Monitor, *pRight );
1612 if ( pNode->m_pRight.load( memory_model::memory_order_relaxed ) != pRight )
1613 return pNode; // retry for pNode
1615 int hR = pRight->height( memory_model::memory_order_relaxed );
1616 if ( hL - hR >= -1 )
1617 return pNode; // retry
1619 node_type * pRLeft = child( pRight, left_child, memory_model::memory_order_relaxed );
1620 int hRL = pRLeft ? pRLeft->height( memory_model::memory_order_relaxed ) : 0;
1621 node_type * pRRight = child( pRight, right_child, memory_model::memory_order_relaxed );
1622 int hRR = pRRight ? pRRight->height( memory_model::memory_order_relaxed ) : 0;
1624 return rotate_left_locked( pParent, pNode, hL, pRight, pRLeft, hRL, hRR );
1627 assert( pRLeft != nullptr );
1628 node_scoped_lock lrl( m_Monitor, *pRLeft );
1629 if ( pRight->m_pLeft.load( memory_model::memory_order_relaxed ) != pRLeft )
1630 return pNode; // retry
1632 hRL = pRLeft->height( memory_model::memory_order_relaxed );
1634 return rotate_left_locked( pParent, pNode, hL, pRight, pRLeft, hRL, hRR );
1636 node_type * pRLRight = child( pRLeft, right_child, memory_model::memory_order_relaxed );
1637 int hRLR = pRLRight ? pRLRight->height( memory_model::memory_order_relaxed ) : 0;
1638 int balance = hRR - hRLR;
1639 if ( balance >= -1 && balance <= 1 && !((hRR == 0 || hRLR == 0) && !pRight->is_valued( memory_model::memory_order_relaxed )))
1640 return rotate_left_over_right_locked( pParent, pNode, hL, pRight, pRLeft, hRR, hRLR );
1642 return rebalance_to_right_locked( pNode, pRight, pRLeft, hRR );
1646 static void begin_change( node_type * pNode, version_type version )
1648 pNode->version( version | node_type::shrinking, memory_model::memory_order_release );
1650 static void end_change( node_type * pNode, version_type version )
1652 // Clear shrinking and unlinked flags and increment version
1653 pNode->version( (version | node_type::version_flags) + 1, memory_model::memory_order_release );
1656 node_type * rotate_right_locked( node_type * pParent, node_type * pNode, node_type * pLeft, int hR, int hLL, node_type * pLRight, int hLR )
1658 version_type nodeVersion = pNode->version( memory_model::memory_order_relaxed );
1659 node_type * pParentLeft = child( pParent, left_child, memory_model::memory_order_relaxed );
1661 begin_change( pNode, nodeVersion );
1663 pNode->m_pLeft.store( pLRight, memory_model::memory_order_relaxed );
1664 if ( pLRight != nullptr )
1665 pLRight->m_pParent.store( pNode, memory_model::memory_order_relaxed );
1667 pLeft->m_pRight.store( pNode, memory_model::memory_order_relaxed );
1668 pNode->m_pParent.store( pLeft, memory_model::memory_order_relaxed );
1670 if ( pParentLeft == pNode )
1671 pParent->m_pLeft.store( pLeft, memory_model::memory_order_relaxed );
1673 assert( pParent->m_pRight.load( memory_model::memory_order_relaxed ) == pNode );
1674 pParent->m_pRight.store( pLeft, memory_model::memory_order_relaxed );
1676 pLeft->m_pParent.store( pParent, memory_model::memory_order_relaxed );
1678 // fix up heights links
1679 int hNode = 1 + std::max( hLR, hR );
1680 pNode->height( hNode, memory_model::memory_order_relaxed );
1681 pLeft->height( 1 + std::max( hLL, hNode ), memory_model::memory_order_relaxed );
1683 end_change( pNode, nodeVersion );
1684 m_stat.onRotateRight();
1686 // We have damaged pParent, pNode (now parent.child.right), and pLeft (now
1687 // parent.child). pNode is the deepest. Perform as many fixes as we can
1688 // with the locks we've got.
1690 // We've already fixed the height for pNode, but it might still be outside
1691 // our allowable balance range. In that case a simple fix_height_locked()
1693 int nodeBalance = hLR - hR;
1694 if ( nodeBalance < -1 || nodeBalance > 1 ) {
1695 // we need another rotation at pNode
1699 // we've fixed balance and height damage for pNode, now handle
1700 // extra-routing node damage
1701 if ( (pLRight == nullptr || hR == 0) && !pNode->is_valued(memory_model::memory_order_relaxed)) {
1702 // we need to remove pNode and then repair
1706 // we've already fixed the height at pLeft, do we need a rotation here?
1707 int leftBalance = hLL - hNode;
1708 if ( leftBalance < -1 || leftBalance > 1 )
1711 // pLeft might also have routing node damage (if pLeft.left was null)
1712 if ( hLL == 0 && !pLeft->is_valued( memory_model::memory_order_relaxed ))
1715 // try to fix the parent height while we've still got the lock
1716 return fix_height_locked( pParent );
1719 node_type * rotate_left_locked( node_type * pParent, node_type * pNode, int hL, node_type * pRight, node_type * pRLeft, int hRL, int hRR )
1721 version_type nodeVersion = pNode->version( memory_model::memory_order_relaxed );
1722 node_type * pParentLeft = child( pParent, left_child, memory_model::memory_order_relaxed );
1724 begin_change( pNode, nodeVersion );
1726 // fix up pNode links, careful to be compatible with concurrent traversal for all but pNode
1727 pNode->m_pRight.store( pRLeft, memory_model::memory_order_relaxed );
1728 if ( pRLeft != nullptr )
1729 pRLeft->m_pParent.store( pNode, memory_model::memory_order_relaxed );
1731 pRight->m_pLeft.store( pNode, memory_model::memory_order_relaxed );
1732 pNode->m_pParent.store( pRight, memory_model::memory_order_relaxed );
1734 if ( pParentLeft == pNode )
1735 pParent->m_pLeft.store( pRight, memory_model::memory_order_relaxed );
1737 assert( pParent->m_pRight.load( memory_model::memory_order_relaxed ) == pNode );
1738 pParent->m_pRight.store( pRight, memory_model::memory_order_relaxed );
1740 pRight->m_pParent.store( pParent, memory_model::memory_order_relaxed );
1743 int hNode = 1 + std::max( hL, hRL );
1744 pNode->height( hNode, memory_model::memory_order_relaxed );
1745 pRight->height( 1 + std::max( hNode, hRR ), memory_model::memory_order_relaxed );
1747 end_change( pNode, nodeVersion );
1748 m_stat.onRotateLeft();
1750 int nodeBalance = hRL - hL;
1751 if ( nodeBalance < -1 || nodeBalance > 1 )
1754 if ( (pRLeft == nullptr || hL == 0) && !pNode->is_valued( memory_model::memory_order_relaxed ))
1757 int rightBalance = hRR - hNode;
1758 if ( rightBalance < -1 || rightBalance > 1 )
1761 if ( hRR == 0 && !pRight->is_valued( memory_model::memory_order_relaxed ))
1764 return fix_height_locked( pParent );
1767 node_type * rotate_right_over_left_locked( node_type * pParent, node_type * pNode, node_type * pLeft, int hR, int hLL, node_type * pLRight, int hLRL )
1769 version_type nodeVersion = pNode->version( memory_model::memory_order_relaxed );
1770 version_type leftVersion = pLeft->version( memory_model::memory_order_relaxed );
1772 node_type * pPL = child( pParent, left_child, memory_model::memory_order_relaxed );
1773 node_type * pLRL = child( pLRight, left_child, memory_model::memory_order_relaxed );
1774 node_type * pLRR = child( pLRight, right_child, memory_model::memory_order_relaxed );
1775 int hLRR = pLRR ? pLRR->height( memory_model::memory_order_relaxed ) : 0;
1777 begin_change( pNode, nodeVersion );
1778 begin_change( pLeft, leftVersion );
1780 // fix up pNode links, careful about the order!
1781 pNode->m_pLeft.store( pLRR, memory_model::memory_order_relaxed );
1782 if ( pLRR != nullptr )
1783 pLRR->m_pParent.store( pNode, memory_model::memory_order_relaxed );
1785 pLeft->m_pRight.store( pLRL, memory_model::memory_order_relaxed );
1786 if ( pLRL != nullptr )
1787 pLRL->m_pParent.store( pLeft, memory_model::memory_order_relaxed );
1789 pLRight->m_pLeft.store( pLeft, memory_model::memory_order_relaxed );
1790 pLeft->m_pParent.store( pLRight, memory_model::memory_order_relaxed );
1791 pLRight->m_pRight.store( pNode, memory_model::memory_order_relaxed );
1792 pNode->m_pParent.store( pLRight, memory_model::memory_order_relaxed );
1795 pParent->m_pLeft.store( pLRight, memory_model::memory_order_relaxed );
1797 assert( child( pParent, right_child, memory_model::memory_order_relaxed ) == pNode );
1798 pParent->m_pRight.store( pLRight, memory_model::memory_order_relaxed );
1800 pLRight->m_pParent.store( pParent, memory_model::memory_order_relaxed );
1803 int hNode = 1 + std::max( hLRR, hR );
1804 pNode->height( hNode, memory_model::memory_order_relaxed );
1805 int hLeft = 1 + std::max( hLL, hLRL );
1806 pLeft->height( hLeft, memory_model::memory_order_relaxed );
1807 pLRight->height( 1 + std::max( hLeft, hNode ), memory_model::memory_order_relaxed );
1809 end_change( pNode, nodeVersion );
1810 end_change( pLeft, leftVersion );
1811 m_stat.onRotateRightOverLeft();
1813 // caller should have performed only a single rotation if pLeft was going
1814 // to end up damaged
1815 assert( hLL - hLRL <= 1 && hLRL - hLL <= 1 );
1816 assert( !((hLL == 0 || pLRL == nullptr) && !pLeft->is_valued( memory_model::memory_order_relaxed )));
1818 // We have damaged pParent, pLR (now parent.child), and pNode (now
1819 // parent.child.right). pNode is the deepest. Perform as many fixes as we
1820 // can with the locks we've got.
1822 // We've already fixed the height for pNode, but it might still be outside
1823 // our allowable balance range. In that case a simple fix_height_locked()
1825 int nodeBalance = hLRR - hR;
1826 if ( nodeBalance < -1 || nodeBalance > 1 ) {
1827 // we need another rotation at pNode
1831 // pNode might also be damaged by being an unnecessary routing node
1832 if ( (pLRR == nullptr || hR == 0) && !pNode->is_valued( memory_model::memory_order_relaxed )) {
1833 // repair involves splicing out pNode and maybe more rotations
1837 // we've already fixed the height at pLRight, do we need a rotation here?
1838 int balanceLR = hLeft - hNode;
1839 if ( balanceLR < -1 || balanceLR > 1 )
1842 // try to fix the parent height while we've still got the lock
1843 return fix_height_locked( pParent );
1846 node_type * rotate_left_over_right_locked( node_type * pParent, node_type * pNode, int hL, node_type * pRight, node_type * pRLeft, int hRR, int hRLR )
1848 version_type nodeVersion = pNode->version( memory_model::memory_order_relaxed );
1849 version_type rightVersion = pRight->version( memory_model::memory_order_relaxed );
1851 node_type * pPL = child( pParent, left_child, memory_model::memory_order_relaxed );
1852 node_type * pRLL = child( pRLeft, left_child, memory_model::memory_order_relaxed );
1853 node_type * pRLR = child( pRLeft, right_child, memory_model::memory_order_relaxed );
1854 int hRLL = pRLL ? pRLL->height( memory_model::memory_order_relaxed ) : 0;
1856 begin_change( pNode, nodeVersion );
1857 begin_change( pRight, rightVersion );
1859 // fix up pNode links, careful about the order!
1860 pNode->m_pRight.store( pRLL, memory_model::memory_order_relaxed );
1861 if ( pRLL != nullptr )
1862 pRLL->m_pParent.store( pNode, memory_model::memory_order_relaxed );
1864 pRight->m_pLeft.store( pRLR, memory_model::memory_order_relaxed );
1865 if ( pRLR != nullptr )
1866 pRLR->m_pParent.store( pRight, memory_model::memory_order_relaxed );
1868 pRLeft->m_pRight.store( pRight, memory_model::memory_order_relaxed );
1869 pRight->m_pParent.store( pRLeft, memory_model::memory_order_relaxed );
1870 pRLeft->m_pLeft.store( pNode, memory_model::memory_order_relaxed );
1871 pNode->m_pParent.store( pRLeft, memory_model::memory_order_relaxed );
1874 pParent->m_pLeft.store( pRLeft, memory_model::memory_order_relaxed );
1876 assert( pParent->m_pRight.load( memory_model::memory_order_relaxed ) == pNode );
1877 pParent->m_pRight.store( pRLeft, memory_model::memory_order_relaxed );
1879 pRLeft->m_pParent.store( pParent, memory_model::memory_order_relaxed );
1882 int hNode = 1 + std::max( hL, hRLL );
1883 pNode->height( hNode, memory_model::memory_order_relaxed );
1884 int hRight = 1 + std::max( hRLR, hRR );
1885 pRight->height( hRight, memory_model::memory_order_relaxed );
1886 pRLeft->height( 1 + std::max( hNode, hRight ), memory_model::memory_order_relaxed );
1888 end_change( pNode, nodeVersion );
1889 end_change( pRight, rightVersion );
1890 m_stat.onRotateLeftOverRight();
1892 assert( hRR - hRLR <= 1 && hRLR - hRR <= 1 );
1894 int nodeBalance = hRLL - hL;
1895 if ( nodeBalance < -1 || nodeBalance > 1 )
1897 if ( (pRLL == nullptr || hL == 0) && !pNode->is_valued( memory_model::memory_order_relaxed ))
1900 int balRL = hRight - hNode;
1901 if ( balRL < -1 || balRL > 1 )
1904 return fix_height_locked( pParent );
1909 }} // namespace cds::container
1911 #endif // #ifndef CDSLIB_CONTAINER_IMPL_BRONSON_AVLTREE_MAP_RCU_H