2 This file is a part of libcds - Concurrent Data Structures library
4 (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016
6 Source code repo: http://github.com/khizmax/libcds/
7 Download: http://sourceforge.net/projects/libcds/files/
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions are met:
12 * Redistributions of source code must retain the above copyright notice, this
13 list of conditions and the following disclaimer.
15 * Redistributions in binary form must reproduce the above copyright notice,
16 this list of conditions and the following disclaimer in the documentation
17 and/or other materials provided with the distribution.
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 #ifndef CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H
32 #define CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H
34 #include <type_traits>
35 #include <cds/container/details/ellen_bintree_base.h>
36 #include <cds/intrusive/impl/ellen_bintree.h>
37 #include <cds/container/details/guarded_ptr_cast.h>
39 namespace cds { namespace container {
41 /// Map based on Ellen's et al binary search tree
42 /** @ingroup cds_nonintrusive_map
43 @ingroup cds_nonintrusive_tree
44 @anchor cds_container_EllenBinTreeMap
47 - [2010] F.Ellen, P.Fatourou, E.Ruppert, F.van Breugel "Non-blocking Binary Search Tree"
49 %EllenBinTreeMap is an unbalanced leaf-oriented binary search tree that implements the <i>map</i>
50 abstract data type. Nodes maintains child pointers but not parent pointers.
51 Every internal node has exactly two children, and all data of type <tt>std::pair<Key const, T></tt>
52 currently in the tree are stored in the leaves. Internal nodes of the tree are used to direct \p find
53 operation along the path to the correct leaf. The keys (of \p Key type) stored in internal nodes
54 may or may not be in the map.
55 Unlike \ref cds_container_EllenBinTreeSet "EllenBinTreeSet" keys are not a part of \p T type.
56 The map can be represented as a set containing <tt>std::pair< Key const, T> </tt> values.
58 Due to \p extract_min and \p extract_max member functions the \p %EllenBinTreeMap can act as
59 a <i>priority queue</i>. In this case you should provide unique compound key, for example,
60 the priority value plus some uniformly distributed random value.
62 @warning Recall the tree is <b>unbalanced</b>. The complexity of operations is <tt>O(log N)</tt>
63 for uniformly distributed random keys, but in the worst case the complexity is <tt>O(N)</tt>.
65 @note In the current implementation we do not use helping technique described in the original paper.
66 In Hazard Pointer schema helping is too complicated and does not give any observable benefits.
67 Instead of helping, when a thread encounters a concurrent operation it just spins waiting for
68 the operation done. Such solution allows greatly simplify implementation of the tree.
70 <b>Template arguments</b> :
71 - \p GC - safe memory reclamation (i.e. light-weight garbage collector) type, like \p cds::gc::HP, \p cds::gc::DHP
72 - \p Key - key type. Should be default-constructible
73 - \p T - value type to be stored in tree's leaf nodes.
74 - \p Traits - map traits, default is \p ellen_bintree::traits
75 It is possible to declare option-based tree with \p ellen_bintree::make_map_traits metafunction
76 instead of \p Traits template argument.
78 @note Do not include <tt><cds/container/impl/ellen_bintree_map.h></tt> header file directly.
79 There are header file for each GC type:
80 - <tt><cds/container/ellen_bintree_map_hp.h></tt> - for Hazard Pointer GC cds::gc::HP
81 - <tt><cds/container/ellen_bintree_map_dhp.h></tt> - for Dynamic Hazard Pointer GC cds::gc::DHP
82 - <tt><cds/container/ellen_bintree_map_rcu.h></tt> - for RCU GC
83 (see \ref cds_container_EllenBinTreeMap_rcu "RCU-based EllenBinTreeMap")
89 #ifdef CDS_DOXYGEN_INVOKED
90 class Traits = ellen_bintree::traits
96 #ifdef CDS_DOXYGEN_INVOKED
97 : public cds::intrusive::EllenBinTree< GC, Key, T, Traits >
99 : public ellen_bintree::details::make_ellen_bintree_map< GC, Key, T, Traits >::type
103 typedef ellen_bintree::details::make_ellen_bintree_map< GC, Key, T, Traits > maker;
104 typedef typename maker::type base_class;
107 typedef GC gc; ///< Garbage collector
108 typedef Key key_type; ///< type of a key stored in the map
109 typedef T mapped_type; ///< type of value stored in the map
110 typedef std::pair< key_type const, mapped_type > value_type ; ///< Key-value pair stored in leaf node of the mp
111 typedef Traits traits; ///< Map traits
113 static_assert( std::is_default_constructible<key_type>::value, "Key should be default constructible type");
115 # ifdef CDS_DOXYGEN_INVOKED
116 typedef implementation_defined key_comparator; ///< key compare functor based on \p Traits::compare and \p Traits::less
118 typedef typename maker::intrusive_traits::compare key_comparator;
120 typedef typename base_class::item_counter item_counter; ///< Item counting policy
121 typedef typename base_class::memory_model memory_model; ///< Memory ordering, see \p cds::opt::memory_model
122 typedef typename base_class::node_allocator node_allocator_type; ///< allocator for maintaining internal node
123 typedef typename base_class::stat stat; ///< internal statistics type
124 typedef typename traits::copy_policy copy_policy; ///< key copy policy
125 typedef typename traits::back_off back_off; ///< Back-off strategy
127 typedef typename traits::allocator allocator_type; ///< Allocator for leaf nodes
128 typedef typename base_class::node_allocator node_allocator; ///< Internal node allocator
129 typedef typename base_class::update_desc_allocator update_desc_allocator; ///< Update descriptor allocator
133 typedef typename base_class::value_type leaf_node;
134 typedef typename base_class::internal_node internal_node;
135 typedef typename base_class::update_desc update_desc;
137 typedef typename maker::cxx_leaf_node_allocator cxx_leaf_node_allocator;
139 typedef std::unique_ptr< leaf_node, typename maker::leaf_deallocator > scoped_node_ptr;
144 typedef typename gc::template guarded_ptr< leaf_node, value_type, details::guarded_ptr_cast_set<leaf_node, value_type> > guarded_ptr;
147 /// Default constructor
156 /// Inserts new node with key and default value
158 The function creates a node with \p key and default value, and then inserts the node created into the map.
161 - The \ref key_type should be constructible from a value of type \p K.
162 In trivial case, \p K is equal to \ref key_type.
163 - The \ref mapped_type should be default-constructible.
165 Returns \p true if inserting successful, \p false otherwise.
167 template <typename K>
168 bool insert( K const& key )
170 return insert_with( key, [](value_type&){} );
175 The function creates a node with copy of \p val value
176 and then inserts the node created into the map.
179 - The \p key_type should be constructible from \p key of type \p K.
180 - The \p value_type should be constructible from \p val of type \p V.
182 Returns \p true if \p val is inserted into the map, \p false otherwise.
184 template <typename K, typename V>
185 bool insert( K const& key, V const& val )
187 scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key, val ));
188 if ( base_class::insert( *pNode ))
196 /// Inserts new node and initialize it by a functor
198 This function inserts new node with key \p key and if inserting is successful then it calls
199 \p func functor with signature
202 void operator()( value_type& item );
206 The argument \p item of user-defined functor \p func is the reference
207 to the map's item inserted:
208 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
209 - <tt>item.second</tt> is a reference to item's value that may be changed.
211 The key_type should be constructible from value of type \p K.
213 The function allows to split creating of new item into two part:
214 - create item from \p key;
215 - insert new item into the map;
216 - if inserting is successful, initialize the value of item by calling \p func functor
218 This can be useful if complete initialization of object of \p value_type is heavyweight and
219 it is preferable that the initialization should be completed only if inserting is successful.
221 template <typename K, typename Func>
222 bool insert_with( const K& key, Func func )
224 scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
225 if ( base_class::insert( *pNode, [&func]( leaf_node& item ) { func( item.m_Value ); } )) {
232 /// For key \p key inserts data of type \p value_type created in-place from \p args
234 Returns \p true if inserting successful, \p false otherwise.
236 template <typename K, typename... Args>
237 bool emplace( K&& key, Args&&... args )
239 scoped_node_ptr pNode( cxx_leaf_node_allocator().MoveNew( key_type( std::forward<K>(key)), mapped_type( std::forward<Args>(args)... )));
240 if ( base_class::insert( *pNode )) {
249 The operation performs inserting or changing data with lock-free manner.
251 If the item \p val is not found in the map, then \p val is inserted iff \p bAllowInsert is \p true.
252 Otherwise, the functor \p func is called with item found.
253 The functor \p func signature is:
256 void operator()( bool bNew, value_type& item );
261 - \p bNew - \p true if the item has been inserted, \p false otherwise
262 - \p item - item of the map
264 The functor may change any fields of the \p item.second that is \ref mapped_type;
265 however, \p func must guarantee that during changing no any other modifications
266 could be made on this item by concurrent threads.
268 Returns std::pair<bool, bool> where \p first is \p true if operation is successful,
269 i.e. the node has been inserted or updated,
270 \p second is \p true if new item has been added or \p false if the item with \p key
273 @warning See \ref cds_intrusive_item_creating "insert item troubleshooting"
275 template <typename K, typename Func>
276 std::pair<bool, bool> update( K const& key, Func func, bool bAllowInsert = true )
278 scoped_node_ptr pNode( cxx_leaf_node_allocator().New( key ));
279 std::pair<bool, bool> res = base_class::update( *pNode,
280 [&func](bool bNew, leaf_node& item, leaf_node const& ){ func( bNew, item.m_Value ); },
283 if ( res.first && res.second )
288 template <typename K, typename Func>
289 CDS_DEPRECATED("ensure() is deprecated, use update()")
290 std::pair<bool, bool> ensure( K const& key, Func func )
292 return update( key, func, true );
296 /// Delete \p key from the map
297 /**\anchor cds_nonintrusive_EllenBinTreeMap_erase_val
299 Return \p true if \p key is found and deleted, \p false otherwise
301 template <typename K>
302 bool erase( K const& key )
304 return base_class::erase(key);
307 /// Deletes the item from the map using \p pred predicate for searching
309 The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_erase_val "erase(K const&)"
310 but \p pred is used for key comparing.
311 \p Less functor has the interface like \p std::less.
312 \p Less must imply the same element order as the comparator used for building the map.
314 template <typename K, typename Less>
315 bool erase_with( K const& key, Less pred )
318 return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
321 /// Delete \p key from the map
322 /** \anchor cds_nonintrusive_EllenBinTreeMap_erase_func
324 The function searches an item with key \p key, calls \p f functor
325 and deletes the item. If \p key is not found, the functor is not called.
327 The functor \p Func interface:
330 void operator()(value_type& item) { ... }
334 Return \p true if key is found and deleted, \p false otherwise
336 template <typename K, typename Func>
337 bool erase( K const& key, Func f )
339 return base_class::erase( key, [&f]( leaf_node& node) { f( node.m_Value ); } );
342 /// Deletes the item from the map using \p pred predicate for searching
344 The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_erase_func "erase(K const&, Func)"
345 but \p pred is used for key comparing.
346 \p Less functor has the interface like \p std::less.
347 \p Less must imply the same element order as the comparator used for building the map.
349 template <typename K, typename Less, typename Func>
350 bool erase_with( K const& key, Less pred, Func f )
353 return base_class::erase_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
354 [&f]( leaf_node& node) { f( node.m_Value ); } );
357 /// Extracts an item with minimal key from the map
359 If the map is not empty, the function returns an guarded pointer to minimum value.
360 If the map is empty, the function returns an empty \p guarded_ptr.
362 @note Due the concurrent nature of the map, the function extracts <i>nearly</i> minimum key.
363 It means that the function gets leftmost leaf of the tree and tries to unlink it.
364 During unlinking, a concurrent thread may insert an item with key less than leftmost item's key.
365 So, the function returns the item with minimum key at the moment of tree traversing.
367 The guarded pointer prevents deallocation of returned item,
368 see \p cds::gc::guarded_ptr for explanation.
369 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
371 guarded_ptr extract_min()
374 base_class::extract_min_( gp.guard() );
378 /// Extracts an item with maximal key from the map
380 If the map is not empty, the function returns a guarded pointer to maximal value.
381 If the map is empty, the function returns an empty \p guarded_ptr.
383 @note Due the concurrent nature of the map, the function extracts <i>nearly</i> maximal key.
384 It means that the function gets rightmost leaf of the tree and tries to unlink it.
385 During unlinking, a concurrent thread may insert an item with key great than leftmost item's key.
386 So, the function returns the item with maximum key at the moment of tree traversing.
388 The guarded pointer prevents deallocation of returned item,
389 see \p cds::gc::guarded_ptr for explanation.
390 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
392 guarded_ptr extract_max()
395 base_class::extract_max_( gp.guard() );
399 /// Extracts an item from the tree
400 /** \anchor cds_nonintrusive_EllenBinTreeMap_extract
401 The function searches an item with key equal to \p key in the tree,
402 unlinks it, and returns a guarded pointer to an item found.
403 If the item is not found the function returns an empty \p guarded_ptr.
405 The guarded pointer prevents deallocation of returned item,
406 see \p cds::gc::guarded_ptr for explanation.
407 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
409 template <typename Q>
410 guarded_ptr extract( Q const& key )
413 base_class::extract_( gp.guard(), key );
417 /// Extracts an item from the map using \p pred for searching
419 The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_extract "extract(Q const&)"
420 but \p pred is used for key compare.
421 \p Less has the interface like \p std::less.
422 \p pred must imply the same element order as the comparator used for building the map.
424 template <typename Q, typename Less>
425 guarded_ptr extract_with( Q const& key, Less pred )
429 base_class::extract_with_( gp.guard(), key,
430 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >());
434 /// Find the key \p key
435 /** \anchor cds_nonintrusive_EllenBinTreeMap_find_cfunc
437 The function searches the item with key equal to \p key and calls the functor \p f for item found.
438 The interface of \p Func functor is:
441 void operator()( value_type& item );
444 where \p item is the item found.
446 The functor may change \p item.second.
448 The function returns \p true if \p key is found, \p false otherwise.
450 template <typename K, typename Func>
451 bool find( K const& key, Func f )
453 return base_class::find( key, [&f](leaf_node& item, K const& ) { f( item.m_Value );});
456 /// Finds the key \p val using \p pred predicate for searching
458 The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_find_cfunc "find(K const&, Func)"
459 but \p pred is used for key comparing.
460 \p Less functor has the interface like \p std::less.
461 \p Less must imply the same element order as the comparator used for building the map.
463 template <typename K, typename Less, typename Func>
464 bool find_with( K const& key, Less pred, Func f )
467 return base_class::find_with( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >(),
468 [&f](leaf_node& item, K const& ) { f( item.m_Value );});
471 /// Checks whether the map contains \p key
473 The function searches the item with key equal to \p key
474 and returns \p true if it is found, and \p false otherwise.
476 template <typename K>
477 bool contains( K const& key )
479 return base_class::contains( key );
482 template <typename K>
483 CDS_DEPRECATED("deprecated, use contains()")
484 bool find( K const& key )
486 return contains( key );
490 /// Checks whether the map contains \p key using \p pred predicate for searching
492 The function is similar to <tt>contains( key )</tt> but \p pred is used for key comparing.
493 \p Less functor has the interface like \p std::less.
494 \p Less must imply the same element order as the comparator used for building the set.
496 template <typename K, typename Less>
497 bool contains( K const& key, Less pred )
500 return base_class::contains( key, cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
503 template <typename K, typename Less>
504 CDS_DEPRECATED("deprecated, use contains()")
505 bool find_with( K const& key, Less pred )
507 return contains( key, pred );
511 /// Finds \p key and returns the item found
512 /** @anchor cds_nonintrusive_EllenBinTreeMap_get
513 The function searches the item with key equal to \p key and returns the item found as a guarded pointer.
514 If \p key is not foudn the function returns an empty \p guarded_ptr.
516 The guarded pointer prevents deallocation of returned item,
517 see \p cds::gc::guarded_ptr for explanation.
518 @note Each \p guarded_ptr object uses the GC's guard that can be limited resource.
520 template <typename Q>
521 guarded_ptr get( Q const& key )
524 base_class::get_( gp.guard(), key );
528 /// Finds \p key with predicate \p pred and returns the item found
530 The function is an analog of \ref cds_nonintrusive_EllenBinTreeMap_get "get(Q const&)"
531 but \p pred is used for key comparing.
532 \p Less functor has the interface like \p std::less.
533 \p pred must imply the same element order as the comparator used for building the map.
535 template <typename Q, typename Less>
536 guarded_ptr get_with( Q const& key, Less pred )
540 base_class::get_with_( gp.guard(), key,
541 cds::details::predicate_wrapper< leaf_node, Less, typename maker::key_accessor >() );
545 /// Clears the map (not atomic)
551 /// Checks if the map is empty
553 Emptiness is checked by item counting: if item count is zero then the map is empty.
557 return base_class::empty();
560 /// Returns item count in the set
562 Only leaf nodes containing user data are counted.
564 The value returned depends on item counter type provided by \p Traits template parameter.
565 If it is \p atomicity::empty_item_counter this function always returns 0.
567 The function is not suitable for checking the tree emptiness, use \p empty()
568 member function for this purpose.
572 return base_class::size();
575 /// Returns const reference to internal statistics
576 stat const& statistics() const
578 return base_class::statistics();
581 /// Checks internal consistency (not atomic, not thread-safe)
583 The debugging function to check internal consistency of the tree.
585 bool check_consistency() const
587 return base_class::check_consistency();
591 }} // namespace cds::container
593 #endif //#ifndef CDSLIB_CONTAINER_IMPL_ELLEN_BINTREE_MAP_H