3 #ifndef __CDS_CONTAINER_IMPL_ELLEN_BINTREE_SET_H
4 #define __CDS_CONTAINER_IMPL_ELLEN_BINTREE_SET_H
7 #include <cds/container/details/ellen_bintree_base.h>
8 #include <cds/intrusive/impl/ellen_bintree.h>
9 #include <cds/container/details/guarded_ptr_cast.h>
11 namespace cds { namespace container {
13 /// Set based on Ellen's et al binary search tree
14 /** @ingroup cds_nonintrusive_set
15 @ingroup cds_nonintrusive_tree
16 @anchor cds_container_EllenBinTreeSet
19 - [2010] F.Ellen, P.Fatourou, E.Ruppert, F.van Breugel "Non-blocking Binary Search Tree"
21 %EllenBinTreeSet is an unbalanced leaf-oriented binary search tree that implements the <i>set</i>
22 abstract data type. Nodes maintains child pointers but not parent pointers.
23 Every internal node has exactly two children, and all data of type \p T currently in
24 the tree are stored in the leaves. Internal nodes of the tree are used to direct \p find
25 operation along the path to the correct leaf. The keys (of \p Key type) stored in internal nodes
26 may or may not be in the set. \p Key type is a subset of \p T type.
27 There should be exactly defined a key extracting functor for converting object of type \p T to
28 object of type \p Key.
30 Due to \p extract_min and \p extract_max member functions the \p %EllenBinTreeSet can act as
31 a <i>priority queue</i>. In this case you should provide unique compound key, for example,
32 the priority value plus some uniformly distributed random value.
34 @warning Recall the tree is <b>unbalanced</b>. The complexity of operations is <tt>O(log N)</tt>
35 for uniformly distributed random keys, but in worst case the complexity is <tt>O(N)</tt>.
37 @note In the current implementation we do not use helping technique described in the original paper.
38 In Hazard Pointer schema helping is too complicated and does not give any observable benefits.
39 Instead of helping, when a thread encounters a concurrent operation it just spins waiting for
40 the operation done. Such solution allows greatly simplify the implementation of tree.
42 <b>Template arguments</b> :
43 - \p GC - safe memory reclamation (i.e. light-weight garbage collector) type, like \p cds::gc::HP, cds::gc::DHP
44 - \p Key - key type, a subset of \p T
45 - \p T - type to be stored in tree's leaf nodes.
46 - \p Traits - set traits, default is \p ellen_bintree::traits
47 It is possible to declare option-based tree with \p ellen_bintree::make_set_traits metafunction
48 instead of \p Traits template argument.
50 @note Do not include <tt><cds/container/impl/ellen_bintree_set.h></tt> header file directly.
51 There are header file for each GC type:
52 - <tt><cds/container/ellen_bintree_set_hp.h></tt> - for \p cds::gc::HP
53 - <tt><cds/container/ellen_bintree_set_dhp.h></tt> - for \p cds::gc::DHP
54 - <tt><cds/container/ellen_bintree_set_rcu.h></tt> - for RCU GC
55 (see \ref cds_container_EllenBinTreeSet_rcu "RCU-based EllenBinTreeSet")
57 @anchor cds_container_EllenBinTreeSet_less
58 <b>Predicate requirements</b>
60 \p Traits::less, \p Traits::compare and other predicates using with member fuctions should accept at least parameters
61 of type \p T and \p Key in any combination.
62 For example, for \p Foo struct with \p std::string key field the appropiate \p less functor is:
71 bool operator()( Foo const& v1, Foo const& v2 ) const
72 { return v1.m_strKey < v2.m_strKey ; }
74 bool operator()( Foo const& v, std::string const& s ) const
75 { return v.m_strKey < s ; }
77 bool operator()( std::string const& s, Foo const& v ) const
78 { return s < v.m_strKey ; }
80 // Support comparing std::string and char const *
81 bool operator()( std::string const& s, char const * p ) const
82 { return s.compare(p) < 0 ; }
84 bool operator()( Foo const& v, char const * p ) const
85 { return v.m_strKey.compare(p) < 0 ; }
87 bool operator()( char const * p, std::string const& s ) const
88 { return s.compare(p) > 0; }
90 bool operator()( char const * p, Foo const& v ) const
91 { return v.m_strKey.compare(p) > 0; }
99 #ifdef CDS_DOXYGEN_INVOKED
100 class Traits = ellen_bintree::traits
105 class EllenBinTreeSet
106 #ifdef CDS_DOXYGEN_INVOKED
107 : public cds::intrusive::EllenBinTree< GC, Key, T, Traits >
109 : public ellen_bintree::details::make_ellen_bintree_set< GC, Key, T, Traits >::type
113 typedef ellen_bintree::details::make_ellen_bintree_set< GC, Key, T, Traits > maker;
114 typedef typename maker::type base_class;
118 typedef GC gc; ///< Garbage collector
119 typedef Key key_type; ///< type of a key to be stored in internal nodes; key is a part of \p value_type
120 typedef T value_type; ///< type of value to be stored in the binary tree
121 typedef Traits traits; ///< Traits template parameter
123 # ifdef CDS_DOXYGEN_INVOKED
124 typedef implementation_defined key_comparator ; ///< key compare functor based on opt::compare and opt::less option setter.
126 typedef typename maker::intrusive_type_traits::compare key_comparator;
128 typedef typename base_class::item_counter item_counter; ///< Item counting policy used
129 typedef typename base_class::memory_model memory_model; ///< Memory ordering. See cds::opt::memory_model option
130 typedef typename base_class::stat stat; ///< internal statistics type
131 typedef typename traits::key_extractor key_extractor; ///< key extracting functor
133 typedef typename traits::allocator allocator_type; ///< Allocator for leaf nodes
134 typedef typename base_class::node_allocator node_allocator; ///< Internal node allocator
135 typedef typename base_class::update_desc_allocator update_desc_allocator; ///< Update descriptor allocator
139 typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
140 typedef typename base_class::value_type leaf_node;
141 typedef typename base_class::internal_node internal_node;
143 typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator > scoped_node_ptr;
148 typedef cds::gc::guarded_ptr< gc, leaf_node, value_type, details::guarded_ptr_cast_set<leaf_node, value_type> > guarded_ptr;
151 /// Default constructor
162 The function creates a node with copy of \p val value
163 and then inserts the node created into the set.
165 The type \p Q should contain at least the complete key for the node.
166 The object of \ref value_type should be constructible from a value of type \p Q.
167 In trivial case, \p Q is equal to \ref value_type.
169 Returns \p true if \p val is inserted into the set, \p false otherwise.
171 template <typename Q>
172 bool insert( Q const& val )
174 scoped_node_ptr sp( cxx_leaf_node_allocator().New( val ));
175 if ( base_class::insert( *sp.get() )) {
184 The function allows to split creating of new item into two part:
185 - create item with key only
186 - insert new item into the set
187 - if inserting is success, calls \p f functor to initialize value-fields of \p val.
189 The functor signature is:
191 void func( value_type& val );
193 where \p val is the item inserted. User-defined functor \p f should guarantee that during changing
194 \p val no any other changes could be made on this set's item by concurrent threads.
195 The user-defined functor is called only if the inserting is success.
197 template <typename Q, typename Func>
198 bool insert( Q const& val, Func f )
200 scoped_node_ptr sp( cxx_leaf_node_allocator().New( val ));
201 if ( base_class::insert( *sp.get(), [&f]( leaf_node& val ) { f( val.m_Value ); } )) {
208 /// Ensures that the item exists in the set
210 The operation performs inserting or changing data with lock-free manner.
212 If the \p val key not found in the set, then the new item created from \p val
213 is inserted into the set. Otherwise, the functor \p func is called with the item found.
214 The functor \p Func should be a function with signature:
216 void func( bool bNew, value_type& item, const Q& val );
221 void operator()( bool bNew, value_type& item, const Q& val );
226 - \p bNew - \p true if the item has been inserted, \p false otherwise
227 - \p item - item of the set
228 - \p val - argument \p key passed into the \p ensure function
230 The functor may change non-key fields of the \p item; however, \p func must guarantee
231 that during changing no any other modifications could be made on this item by concurrent threads.
233 Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
234 \p second is true if new item has been added or \p false if the item with \p key
235 already is in the set.
237 @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
239 template <typename Q, typename Func>
240 std::pair<bool, bool> ensure( const Q& val, Func func )
242 scoped_node_ptr sp( cxx_leaf_node_allocator().New( val ));
243 std::pair<bool, bool> bRes = base_class::ensure( *sp,
244 [&func, &val](bool bNew, leaf_node& node, leaf_node&){ func( bNew, node.m_Value, val ); });
245 if ( bRes.first && bRes.second )
250 /// Inserts data of type \p value_type created in-place from \p args
252 Returns \p true if inserting successful, \p false otherwise.
254 template <typename... Args>
255 bool emplace( Args&&... args )
257 scoped_node_ptr sp( cxx_leaf_node_allocator().New( std::forward<Args>(args)... ));
258 if ( base_class::insert( *sp.get() )) {
265 /// Delete \p key from the set
266 /** \anchor cds_nonintrusive_EllenBinTreeSet_erase_val
268 The item comparator should be able to compare the type \p value_type
271 Return \p true if key is found and deleted, \p false otherwise
273 template <typename Q>
274 bool erase( Q const& key )
276 return base_class::erase( key );
279 /// Deletes the item from the set using \p pred predicate for searching
281 The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_erase_val "erase(Q const&)"
282 but \p pred is used for key comparing.
283 \p Less functor has the interface like \p std::less.
284 \p Less must imply the same element order as the comparator used for building the set.
286 template <typename Q, typename Less>
287 bool erase_with( Q const& key, Less pred )
289 return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >());
292 /// Delete \p key from the set
293 /** \anchor cds_nonintrusive_EllenBinTreeSet_erase_func
295 The function searches an item with key \p key, calls \p f functor
296 and deletes the item. If \p key is not found, the functor is not called.
298 The functor \p Func interface:
301 void operator()(value_type const& val);
305 Since the key of MichaelHashSet's \p value_type is not explicitly specified,
306 template parameter \p Q defines the key type searching in the list.
307 The list item comparator should be able to compare the type \p T of list item
310 Return \p true if key is found and deleted, \p false otherwise
312 template <typename Q, typename Func>
313 bool erase( Q const& key, Func f )
315 return base_class::erase( key, [&f]( leaf_node const& node) { f( node.m_Value ); } );
318 /// Deletes the item from the set using \p pred predicate for searching
320 The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_erase_func "erase(Q const&, Func)"
321 but \p pred is used for key comparing.
322 \p Less functor has the interface like \p std::less.
323 \p Less must imply the same element order as the comparator used for building the set.
325 template <typename Q, typename Less, typename Func>
326 bool erase_with( Q const& key, Less pred, Func f )
328 return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >(),
329 [&f]( leaf_node const& node) { f( node.m_Value ); } );
332 /// Extracts an item with minimal key from the set
334 If the set is not empty, the function returns \p true, \p result contains a pointer to minimum value.
335 If the set is empty, the function returns \p false, \p result is left unchanged.
337 @note Due the concurrent nature of the set, the function extracts <i>nearly</i> minimum key.
338 It means that the function gets leftmost leaf of the tree and tries to unlink it.
339 During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
340 So, the function returns the item with minimum key at the moment of tree traversing.
342 The guarded pointer \p dest prevents deallocation of returned item,
343 see cds::gc::guarded_ptr for explanation.
344 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
346 bool extract_min( guarded_ptr& result )
348 return base_class::extract_min_( result.guard() );
351 /// Extracts an item with maximal key from the set
353 If the set is not empty, the function returns \p true, \p result contains a pointer to maximal value.
354 If the set is empty, the function returns \p false, \p result is left unchanged.
356 @note Due the concurrent nature of the set, the function extracts <i>nearly</i> maximal key.
357 It means that the function gets rightmost leaf of the tree and tries to unlink it.
358 During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
359 So, the function returns the item with maximum key at the moment of tree traversing.
361 The guarded pointer \p dest prevents deallocation of returned item,
362 see cds::gc::guarded_ptr for explanation.
363 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
365 bool extract_max( guarded_ptr& result )
367 return base_class::extract_max_( result.guard() );
370 /// Extracts an item from the tree
371 /** \anchor cds_nonintrusive_EllenBinTreeSet_extract
372 The function searches an item with key equal to \p key in the tree,
373 unlinks it, and returns pointer to an item found in \p result parameter.
374 If the item is not found the function returns \p false.
376 The guarded pointer \p dest prevents deallocation of returned item,
377 see cds::gc::guarded_ptr for explanation.
378 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
380 template <typename Q>
381 bool extract( guarded_ptr& result, Q const& key )
383 return base_class::extract_( result.guard(), key );
386 /// Extracts an item from the set using \p pred for searching
388 The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_extract "extract(guarded_ptr& dest, Q const&)"
389 but \p pred is used for key compare.
390 \p Less has the interface like \p std::less.
391 \p pred must imply the same element order as the comparator used for building the set.
393 template <typename Q, typename Less>
394 bool extract_with( guarded_ptr& result, Q const& key, Less pred )
396 return base_class::extract_with_( result.guard(), key,
397 cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >());
400 /// Find the key \p key
402 @anchor cds_nonintrusive_EllenBinTreeSet_find_func
404 The function searches the item with key equal to \p key and calls the functor \p f for item found.
405 The interface of \p Func functor is:
408 void operator()( value_type& item, Q& key );
411 where \p item is the item found, \p key is the <tt>find</tt> function argument.
413 You may pass \p f argument by reference using \p std::ref.
415 The functor may change non-key fields of \p item. Note that the functor is only guarantee
416 that \p item cannot be disposed during functor is executing.
417 The functor does not serialize simultaneous access to the set's \p item. If such access is
418 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
420 The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
421 can modify both arguments.
423 Note the hash functor specified for class \p Traits template parameter
424 should accept a parameter of type \p Q that may be not the same as \p value_type.
426 The function returns \p true if \p key is found, \p false otherwise.
428 template <typename Q, typename Func>
429 bool find( Q& key, Func f )
431 return base_class::find( key, [&f]( leaf_node& node, Q& v ) { f( node.m_Value, v ); });
434 template <typename Q, typename Func>
435 bool find( Q const& key, Func f )
437 return base_class::find( key, [&f]( leaf_node& node, Q const& v ) { f( node.m_Value, v ); } );
441 /// Finds the key \p key using \p pred predicate for searching
443 The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_find_func "find(Q&, Func)"
444 but \p pred is used for key comparing.
445 \p Less functor has the interface like \p std::less.
446 \p Less must imply the same element order as the comparator used for building the set.
448 template <typename Q, typename Less, typename Func>
449 bool find_with( Q& key, Less pred, Func f )
451 return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >(),
452 [&f]( leaf_node& node, Q& v ) { f( node.m_Value, v ); } );
455 template <typename Q, typename Less, typename Func>
456 bool find_with( Q const& key, Less pred, Func f )
458 return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >(),
459 [&f]( leaf_node& node, Q const& v ) { f( node.m_Value, v ); } );
463 /// Find the key \p key
464 /** @anchor cds_nonintrusive_EllenBinTreeSet_find_val
466 The function searches the item with key equal to \p key
467 and returns \p true if it is found, and \p false otherwise.
469 Note the hash functor specified for class \p Traits template parameter
470 should accept a parameter of type \p Q that may be not the same as \ref value_type.
472 template <typename Q>
473 bool find( Q const & key )
475 return base_class::find( key );
478 /// Finds the key \p key using \p pred predicate for searching
480 The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_find_val "find(Q const&)"
481 but \p pred is used for key comparing.
482 \p Less functor has the interface like \p std::less.
483 \p Less must imply the same element order as the comparator used for building the set.
485 template <typename Q, typename Less>
486 bool find_with( Q const& key, Less pred )
488 return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >());
491 /// Finds \p key and returns the item found
492 /** @anchor cds_nonintrusive_EllenBinTreeSet_get
493 The function searches the item with key equal to \p key and returns the item found in \p result parameter.
494 The function returns \p true if \p key is found, \p false otherwise.
496 The guarded pointer \p dest prevents deallocation of returned item,
497 see cds::gc::guarded_ptr for explanation.
498 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
500 template <typename Q>
501 bool get( guarded_ptr& result, Q const& key )
503 return base_class::get_( result.guard(), key );
506 /// Finds \p key with predicate \p pred and returns the item found
508 The function is an analog of \ref cds_nonintrusive_EllenBinTreeSet_get "get(guarded_ptr&, Q const&)"
509 but \p pred is used for key comparing.
510 \p Less functor has the interface like \p std::less.
511 \p pred must imply the same element order as the comparator used for building the set.
513 template <typename Q, typename Less>
514 bool get_with( guarded_ptr& result, Q const& key, Less pred )
516 return base_class::get_with_( result.guard(), key,
517 cds::details::predicate_wrapper< leaf_node, Less, typename maker::value_accessor >() );
520 /// Clears the set (not atomic)
522 The function unlink all items from the tree.
523 The function is not atomic, thus, in multi-threaded environment with parallel insertions
527 assert( set.empty() );
529 the assertion could be raised.
531 For each leaf the \ref disposer will be called after unlinking.
538 /// Checks if the set is empty
541 return base_class::empty();
544 /// Returns item count in the set
546 Only leaf nodes containing user data are counted.
548 The value returned depends on item counter type provided by \p Traits template parameter.
549 If it is \p atomicity::empty_item_counter this function always returns 0.
551 The function is not suitable for checking the tree emptiness, use \p empty()
552 member function for this purpose.
556 return base_class::size();
559 /// Returns const reference to internal statistics
560 stat const& statistics() const
562 return base_class::statistics();
565 /// Checks internal consistency (not atomic, not thread-safe)
567 The debugging function to check internal consistency of the tree.
569 bool check_consistency() const
571 return base_class::check_consistency();
575 }} // namespace cds::container
577 #endif // #ifndef __CDS_CONTAINER_IMPL_ELLEN_BINTREE_SET_H