a363c656ba4150f400192c6363bd1961184e16cc
[libcds.git] / cds / container / split_list_map_rcu.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_SPLIT_LIST_MAP_RCU_H
4 #define __CDS_CONTAINER_SPLIT_LIST_MAP_RCU_H
5
6 #include <cds/container/split_list_set_rcu.h>
7 #include <cds/details/binary_functor_wrapper.h>
8
9 namespace cds { namespace container {
10
11     /// Split-ordered list map (template specialization for \ref cds_urcu_desc "RCU")
12     /** @ingroup cds_nonintrusive_map
13         \anchor cds_nonintrusive_SplitListMap_rcu
14
15         Hash table implementation based on split-ordered list algorithm discovered by Ori Shalev and Nir Shavit, see
16         - [2003] Ori Shalev, Nir Shavit "Split-Ordered Lists - Lock-free Resizable Hash Tables"
17         - [2008] Nir Shavit "The Art of Multiprocessor Programming"
18
19         See intrusive::SplitListSet for a brief description of the split-list algorithm.
20
21         Template parameters:
22         - \p RCU - one of \ref cds_urcu_gc "RCU type"
23         - \p Key - key type to be stored in the map
24         - \p Value - value type to be stored in the map
25         - \p Traits - type traits, default is \p split_list::traits. Instead of declaring \p %split_list::traits -based
26             struct you may apply option-based notation with \p split_list::make_traits metafunction.
27
28         <b>Iterators</b>
29
30         The class supports a forward unordered iterator (\ref iterator and \ref const_iterator).
31         You may iterate over split-list map items only under RCU lock.
32         Only in this case the iterator is thread-safe since
33         while RCU is locked any map's item cannot be reclaimed.
34         The requirement of RCU lock during iterating means that deletion of the elements
35         is not possible.
36
37         @warning The iterator object cannot be passed between threads.
38         Due to concurrent nature of split-list map it is not guarantee that you can iterate
39         all elements in the map: any concurrent deletion can exclude the element
40         pointed by the iterator from the map, and your iteration can be terminated
41         before end of the map. Therefore, such iteration is more suitable for debugging purposes
42
43         The iterator class supports the following minimalistic interface:
44         \code
45         struct iterator {
46             // Default ctor
47             iterator();
48
49             // Copy ctor
50             iterator( iterator const& s);
51
52             value_type * operator ->() const;
53             value_type& operator *() const;
54
55             // Pre-increment
56             iterator& operator ++();
57
58             // Copy assignment
59             iterator& operator = (const iterator& src);
60
61             bool operator ==(iterator const& i ) const;
62             bool operator !=(iterator const& i ) const;
63         };
64         \endcode
65         Note, the iterator object returned by \ref end, \p cend member functions points to \p nullptr and should not be dereferenced.
66
67         \par Usage
68
69         You should decide what garbage collector you want, and what ordered list you want to use. Split-ordered list
70         is original data structure based on an ordered list. Suppose, you want construct split-list map based on \p cds::urcu::general_buffered<> GC
71         and \p MichaelList as ordered list implementation. Your map should map \p int key to \p std::string value.
72         So, you beginning your program with following include:
73         \code
74         #include <cds/urcu/general_buffered.h>
75         #include <cds/container/michael_list_rcu.h>
76         #include <cds/container/split_list_map_rcu.h>
77
78         namespace cc = cds::container;
79         \endcode
80         The inclusion order is important:
81         - first, include one of \ref cds_urcu_gc "RCU implementation" (<tt>cds/urcu/general_buffered.h</tt> in our case)
82         - second, include the header of ordered-list implementation (for this example, <tt>cds/container/michael_list_rcu.h</tt>),
83         - then, the header for RCU-based split-list map <tt>cds/container/split_list_map_rcu.h</tt>.
84
85         Now, you should declare traits for split-list map. The main parts of traits are a hash functor for the map key and a comparing functor for ordered list.
86         We use \p std::hash<int> and \p std::less<int>.
87
88         The second attention: instead of using \p %MichaelList in \p %SplitListMap traits we use a tag \p ds::contaner::michael_list_tag
89         for the Michael's list.
90         The split-list requires significant support from underlying ordered list class and it is not good idea to dive you
91         into deep implementation details of split-list and ordered list interrelations. The tag paradigm simplifies split-list interface.
92
93         \code
94         // SplitListMap traits
95         struct foo_set_traits: public cc::split_list::traits
96         {
97             typedef cc::michael_list_tag   ordered_list    ;   // what type of ordered list we want to use
98             typedef std::hash<int>         hash            ;   // hash functor for the key stored in split-list map
99
100             // Type traits for our MichaelList class
101             struct ordered_list_traits: public cc::michael_list::traits
102             {
103                 typedef std::less<int> less   ;   // use our std::less predicate as comparator to order list nodes
104             };
105         };
106         \endcode
107
108         Now you are ready to declare our map class based on \p %SplitListMap:
109         \code
110         typedef cc::SplitListMap< cds::urcu::gc<cds::urcu::general_buffered<> >, int, std::string, foo_set_traits > int_string_map;
111         \endcode
112
113         You may use the modern option-based declaration instead of classic traits-based one:
114         \code
115         typedef cc:SplitListMap<
116             cds::urcu::gc<cds::urcu::general_buffered<> >  // RCU type
117             ,int                    // key type
118             ,std::string            // value type
119             ,cc::split_list::make_traits<      // metafunction to build split-list traits
120                 cc::split_list::ordered_list<cc::michael_list_tag>     // tag for underlying ordered list implementation
121                 ,cc::opt::hash< std::hash<int> >        // hash functor
122                 ,cc::split_list::ordered_list_traits<    // ordered list traits desired
123                     cc::michael_list::make_traits<    // metafunction to build lazy list traits
124                         cc::opt::less< std::less<int> >         // less-based compare functor
125                     >::type
126                 >
127             >::type
128         >  int_string_map;
129         \endcode
130         In case of option-based declaration using \p split_list::make_traits metafunction the struct \p foo_set_traits is not required.
131
132         Now, the map of type \p int_string_map is ready to use in your program.
133
134         Note that in this example we show only mandatory \p traits parts, optional ones is the default and they are inherited
135         from cds::container::split_list::traits.
136         There are many other useful options for deep tuning the split-list and ordered-list containers.
137     */
138     template <
139         class RCU,
140         typename Key,
141         typename Value,
142 #ifdef CDS_DOXYGEN_INVOKED
143         class Traits = split_list::traits
144 #else
145         class Traits
146 #endif
147     >
148     class SplitListMap< cds::urcu::gc< RCU >, Key, Value, Traits >:
149         protected container::SplitListSet<
150             cds::urcu::gc< RCU >,
151             std::pair<Key const, Value>,
152             split_list::details::wrap_map_traits<Key, Value, Traits>
153         >
154     {
155         //@cond
156         typedef container::SplitListSet<
157             cds::urcu::gc< RCU >,
158             std::pair<Key const, Value>,
159             split_list::details::wrap_map_traits<Key, Value, Traits>
160         >  base_class;
161         //@endcond
162
163     public:
164         typedef cds::urcu::gc< RCU > gc; ///< Garbage collector
165         typedef Key     key_type;    ///< key type
166         typedef Value   mapped_type; ///< type of value to be stored in the map
167         typedef Traits  traits;     ///< Map traits
168
169         typedef std::pair<key_type const, mapped_type> value_type;     ///< key-value pair type
170         typedef typename base_class::ordered_list      ordered_list;   ///< Underlying ordered list class
171         typedef typename base_class::key_comparator    key_comparator; ///< key comparison functor
172
173         typedef typename base_class::hash           hash;         ///< Hash functor for \ref key_type
174         typedef typename base_class::item_counter   item_counter; ///< Item counter type
175         typedef typename base_class::stat           stat;         ///< Internal statistics
176
177         typedef typename base_class::rcu_lock       rcu_lock;   ///< RCU scoped lock
178         typedef typename base_class::exempt_ptr     exempt_ptr; ///< pointer to extracted node
179         /// Group of \p extract_xxx functions require external locking if underlying ordered list requires that
180         static CDS_CONSTEXPR const bool c_bExtractLockExternal = base_class::c_bExtractLockExternal;
181
182     protected:
183         //@cond
184         typedef typename base_class::maker::traits::key_accessor key_accessor;
185         //@endcond
186
187     public:
188         /// Forward iterator
189         typedef typename base_class::iterator iterator;
190
191         /// Const forward iterator
192         typedef typename base_class::const_iterator const_iterator;
193
194         /// Returns a forward iterator addressing the first element in a map
195         /**
196             For empty map \code begin() == end() \endcode
197         */
198         iterator begin()
199         {
200             return base_class::begin();
201         }
202
203         /// Returns an iterator that addresses the location succeeding the last element in a map
204         /**
205             Do not use the value returned by <tt>end</tt> function to access any item.
206             The returned value can be used only to control reaching the end of the map.
207             For empty map \code begin() == end() \endcode
208         */
209         iterator end()
210         {
211             return base_class::end();
212         }
213
214         /// Returns a forward const iterator addressing the first element in a map
215         //@{
216         const_iterator begin() const
217         {
218             return base_class::begin();
219         }
220         const_iterator cbegin() const
221         {
222             return base_class::cbegin();
223         }
224         //@}
225
226         /// Returns an const iterator that addresses the location succeeding the last element in a map
227         //@{
228         const_iterator end() const
229         {
230             return base_class::end();
231         }
232         const_iterator cend() const
233         {
234             return base_class::cend();
235         }
236         //@}
237
238     public:
239         /// Initializes split-ordered map of default capacity
240         /**
241             The default capacity is defined in bucket table constructor.
242             See \p intrusive::split_list::expandable_bucket_table, \p intrusive::split_list::static_bucket_table
243             which selects by \p split_list::dynamic_bucket_table option.
244         */
245         SplitListMap()
246             : base_class()
247         {}
248
249         /// Initializes split-ordered map
250         SplitListMap(
251             size_t nItemCount           ///< estimated average item count
252             , size_t nLoadFactor = 1    ///< load factor - average item count per bucket. Small integer up to 10, default is 1.
253             )
254             : base_class( nItemCount, nLoadFactor )
255         {}
256
257     public:
258         /// Inserts new node with key and default value
259         /**
260             The function creates a node with \p key and the default value, and then inserts the node created into the map.
261
262             Preconditions:
263             - The \p key_type should be constructible from value of type \p K.
264             - The \p mapped_type should be default-constructible.
265
266             The function applies RCU lock internally.
267
268             Returns \p true if inserting successful, \p false otherwise.
269         */
270         template <typename K>
271         bool insert( K const& key )
272         {
273             //TODO: pass arguments by reference (make_pair makes copy)
274             return base_class::insert( std::make_pair( key, mapped_type() ) );
275         }
276
277         /// Inserts new node
278         /**
279             The function creates a node with copy of \p val value
280             and then inserts the node into the map.
281
282             Preconditions:
283             - The \p key_type should be constructible from \p key of type \p K.
284             - The \p mapped_type should be constructible from \p val of type \p V.
285
286             The function applies RCU lock internally.
287
288             Returns \p true if \p val is inserted into the map, \p false otherwise.
289         */
290         template <typename K, typename V>
291         bool insert( K const& key, V const& val )
292         {
293             //TODO: pass arguments by reference (make_pair makes copy)
294             return base_class::insert( std::make_pair(key, val) );
295         }
296
297         /// Inserts new node and initialize it by a functor
298         /**
299             This function inserts new node with key \p key and if inserting is successful then it calls
300             \p func functor with signature
301             \code
302                 struct functor {
303                     void operator()( value_type& item );
304                 };
305             \endcode
306
307             The argument \p item of user-defined functor \p func is the reference
308             to the map's item inserted:
309                 - <tt>item.first</tt> is a const reference to item's key that cannot be changed.
310                 - <tt>item.second</tt> is a reference to item's value that may be changed.
311
312             It should be keep in mind that concurrent modifications of \p <tt>item.second</tt> in \p func body
313             should be careful. You shouldf guarantee that during changing item's value in \p func no any other changes
314             could be made on this \p item by concurrent threads.
315
316             \p func is called only if inserting is successful.
317
318             The function allows to split creating of new item into two part:
319             - create item from \p key;
320             - insert new item into the map;
321             - if inserting is successful, initialize the value of item by calling \p func functor
322
323             This can be useful if complete initialization of object of \p mapped_type is heavyweight and
324             it is preferable that the initialization should be completed only if inserting is successful.
325
326             The function applies RCU lock internally.
327         */
328         template <typename K, typename Func>
329         bool insert_key( K const& key, Func func )
330         {
331             //TODO: pass arguments by reference (make_pair makes copy)
332             return base_class::insert( std::make_pair( key, mapped_type() ), func );
333         }
334
335         /// For key \p key inserts data of type \p mapped_type created in-place from \p args
336         /**
337             \p key_type should be constructible from type \p K
338
339             The function applies RCU lock internally.
340
341             Returns \p true if inserting successful, \p false otherwise.
342         */
343         template <typename K, typename... Args>
344         bool emplace( K&& key, Args&&... args )
345         {
346             return base_class::emplace( std::forward<K>(key), std::move(mapped_type(std::forward<Args>(args)...)));
347         }
348
349         /// Ensures that the \p key exists in the map
350         /**
351             The operation performs inserting or changing data with lock-free manner.
352
353             If the \p key not found in the map, then the new item created from \p key
354             is inserted into the map; in this case the \p key_type should be
355             constructible from type \p K.
356             Otherwise, the functor \p func is called with item found.
357             The functor \p Func signature is:
358             \code
359                 struct my_functor {
360                     void operator()( bool bNew, value_type& item );
361                 };
362             \endcode
363             with arguments:
364             - \p bNew - \p true if the item has been inserted, \p false otherwise
365             - \p item - item of the list
366
367             The functor may change any fields of the \p item.second that is \p mapped_type;
368             however, \p func must guarantee that during changing no any other modifications
369             could be made on this item by concurrent threads.
370
371             The function applies RCU lock internally.
372
373             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
374             \p second is true if new item has been added or \p false if the item with \p key
375             already is in the list.
376
377             @warning For \ref cds_nonintrusive_MichaelKVList_gc "MichaelKVList" as the ordered list see \ref cds_intrusive_item_creating "insert item troubleshooting".
378             \ref cds_nonintrusive_LazyKVList_gc "LazyKVList" provides exclusive access to inserted item and does not require any node-level
379             synchronization.
380         */
381         template <typename K, typename Func>
382         std::pair<bool, bool> ensure( K const& key, Func func )
383         {
384             //TODO: pass arguments by reference (make_pair makes copy)
385             return base_class::ensure( std::make_pair( key, mapped_type() ),
386                 [&func](bool bNew, value_type& item, value_type const& /*val*/) {
387                     func( bNew, item );
388                 } );
389         }
390
391         /// Deletes \p key from the map
392         /** \anchor cds_nonintrusive_SplitListMap_rcu_erase_val
393
394             RCU \p synchronize method can be called. RCU should not be locked.
395
396             Return \p true if \p key is found and deleted, \p false otherwise
397         */
398         template <typename K>
399         bool erase( K const& key )
400         {
401             return base_class::erase( key );
402         }
403
404         /// Deletes the item from the map using \p pred predicate for searching
405         /**
406             The function is an analog of \ref cds_nonintrusive_SplitListMap_rcu_erase_val "erase(K const&)"
407             but \p pred is used for key comparing.
408             \p Less functor has the interface like \p std::less.
409             \p Less must imply the same element order as the comparator used for building the map.
410         */
411         template <typename K, typename Less>
412         bool erase_with( K const& key, Less pred )
413         {
414             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
415         }
416
417         /// Deletes \p key from the map
418         /** \anchor cds_nonintrusive_SplitListMap_rcu_erase_func
419
420             The function searches an item with key \p key, calls \p f functor
421             and deletes the item. If \p key is not found, the functor is not called.
422
423             The functor \p Func interface is:
424             \code
425             struct extractor {
426                 void operator()(value_type& item) { ... }
427             };
428             \endcode
429             The functor may be passed by reference using <tt>boost:ref</tt>
430
431             RCU \p synchronize method can be called. RCU should not be locked.
432
433             Return \p true if key is found and deleted, \p false otherwise
434         */
435         template <typename K, typename Func>
436         bool erase( K const& key, Func f )
437         {
438             return base_class::erase( key, f );
439         }
440
441         /// Deletes the item from the map using \p pred predicate for searching
442         /**
443             The function is an analog of \ref cds_nonintrusive_SplitListMap_rcu_erase_func "erase(K const&, 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 map.
447         */
448         template <typename K, typename Less, typename Func>
449         bool erase_with( K const& key, Less pred, Func f )
450         {
451             return base_class::erase_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>(), f );
452         }
453
454         /// Extracts an item from the map
455         /** \anchor cds_nonintrusive_SplitListMap_rcu_extract
456             The function searches an item with key equal to \p key in the map,
457             unlinks it from the map, places item pointer into \p dest argument, and returns \p true.
458             If the item with the key equal to \p key is not found the function return \p false.
459
460             @note The function does NOT call RCU read-side lock or synchronization,
461             and does NOT dispose the item found. It just excludes the item from the map
462             and returns a pointer to item found.
463             You should lock RCU before calling of the function, and you should synchronize RCU
464             outside the RCU lock to free extracted item
465
466             \code
467             typedef cds::urcu::gc< general_buffered<> > rcu;
468             typedef cds::container::SplitListMap< rcu, int, Foo > splitlist_map;
469
470             splitlist_map theMap;
471             // ...
472
473             typename splitlist_map::exempt_ptr p;
474             {
475                 // first, we should lock RCU
476                 typename splitlist_map::rcu_lock lock;
477
478                 // Now, you can apply extract function
479                 // Note that you must not delete the item found inside the RCU lock
480                 if ( theMap.extract( p, 10 )) {
481                     // do something with p
482                     ...
483                 }
484             }
485
486             // We may safely release p here
487             // release() passes the pointer to RCU reclamation cycle
488             p.release();
489             \endcode
490         */
491         template <typename K>
492         bool extract( exempt_ptr& dest, K const& key )
493         {
494             return base_class::extract( dest, key );
495         }
496
497         /// Extracts an item from the map using \p pred predicate for searching
498         /**
499             The function is an analog of \ref cds_nonintrusive_SplitListMap_rcu_extract "extract(exempt_ptr&, K const&)"
500             but \p pred is used for key comparing.
501             \p Less functor has the interface like \p std::less.
502             \p pred must imply the same element order as the comparator used for building the map.
503         */
504         template <typename K, typename Less>
505         bool extract_with( exempt_ptr& dest, K const& key, Less pred )
506         {
507             return base_class::extract_with( dest, key, cds::details::predicate_wrapper<value_type, Less, key_accessor>());
508         }
509
510         /// Finds the key \p key
511         /** \anchor cds_nonintrusive_SplitListMap_rcu_find_cfunc
512
513             The function searches the item with key equal to \p key and calls the functor \p f for item found.
514             The interface of \p Func functor is:
515             \code
516             struct functor {
517                 void operator()( value_type& item );
518             };
519             \endcode
520             where \p item is the item found.
521
522             You may pass \p f argument by reference using \p std::ref.
523
524             The functor may change \p item.second. Note that the functor is only guarantee
525             that \p item cannot be disposed during functor is executing.
526             The functor does not serialize simultaneous access to the map's \p item. If such access is
527             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
528
529             The function applies RCU lock internally.
530
531             The function returns \p true if \p key is found, \p false otherwise.
532         */
533         template <typename K, typename Func>
534         bool find( K const& key, Func f )
535         {
536             return base_class::find( key, [&f](value_type& pair, K const&){ f( pair ); } );
537         }
538
539         /// Finds the key \p key using \p pred predicate for searching
540         /**
541             The function is an analog of \ref cds_nonintrusive_SplitListMap_rcu_find_cfunc "find(K const&, Func)"
542             but \p pred is used for key comparing.
543             \p Less functor has the interface like \p std::less.
544             \p Less must imply the same element order as the comparator used for building the map.
545         */
546         template <typename K, typename Less, typename Func>
547         bool find_with( K const& key, Less pred, Func f )
548         {
549             return base_class::find_with( key,
550                 cds::details::predicate_wrapper<value_type, Less, key_accessor>(),
551                 [&f](value_type& pair, K const&){ f( pair ); } );
552         }
553
554         /// Finds the key \p key
555         /** \anchor cds_nonintrusive_SplitListMap_rcu_find_val
556
557             The function searches the item with key equal to \p key
558             and returns \p true if it is found, and \p false otherwise.
559
560             The function applies RCU lock internally.
561         */
562         template <typename K>
563         bool find( K const& key )
564         {
565             return base_class::find( key );
566         }
567
568         /// Finds the key \p key using \p pred predicate for searching
569         /**
570             The function is an analog of \ref cds_nonintrusive_SplitListMap_rcu_find_val "find(K const&)"
571             but \p pred is used for key comparing.
572             \p Less functor has the interface like \p std::less.
573             \p Less must imply the same element order as the comparator used for building the map.
574         */
575         template <typename K, typename Less>
576         bool find_with( K const& key, Less pred )
577         {
578             return base_class::find_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>() );
579         }
580
581         /// Finds \p key and return the item found
582         /** \anchor cds_intrusive_SplitListMap_rcu_get
583             The function searches the item with key equal to \p key and returns the pointer to item found.
584             If \p key is not found it returns \p nullptr.
585
586             Note the compare functor should accept a parameter of type \p K that can be not the same as \p value_type.
587
588             RCU should be locked before call of this function.
589             Returned item is valid only while RCU is locked:
590             \code
591             typedef cds::urcu::gc< general_buffered<> > rcu;
592             typedef cds::container::SplitListMap< rcu, int, Foo > splitlist_map;
593             splitlist_map theMap;
594             // ...
595             {
596                 // Lock RCU
597                 typename splitlist_map::rcu_lock lock;
598
599                 typename splitlist_map::value_type * pVal = theMap.get( 5 );
600                 if ( pVal ) {
601                     // Deal with pVal
602                     //...
603                 }
604                 // Unlock RCU by rcu_lock destructor
605                 // pVal can be retired by disposer at any time after RCU has been unlocked
606             }
607             \endcode
608         */
609         template <typename K>
610         value_type * get( K const& key )
611         {
612             return base_class::get( key );
613         }
614
615         /// Finds \p key with predicate specified and return the item found
616         /**
617             The function is an analog of \ref cds_intrusive_SplitListMap_rcu_get "get(K const&)"
618             but \p pred is used for comparing the keys.
619
620             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p K
621             in any order.
622             \p pred must imply the same element order as the comparator used for building the map.
623         */
624         template <typename K, typename Less>
625         value_type * get_with( K const& key, Less pred )
626         {
627             return base_class::get_with( key, cds::details::predicate_wrapper<value_type, Less, key_accessor>());
628         }
629
630         /// Clears the map (not atomic)
631         void clear()
632         {
633             base_class::clear();
634         }
635
636         /// Checks if the map is empty
637         /**
638             Emptiness is checked by item counting: if item count is zero then the map is empty.
639             Thus, the correct item counting is an important part of the map implementation.
640         */
641         bool empty() const
642         {
643             return base_class::empty();
644         }
645
646         /// Returns item count in the map
647         size_t size() const
648         {
649             return base_class::size();
650         }
651
652         /// Returns internal statistics
653         stat const& statistics() const
654         {
655             return base_class::statistics();
656         }
657     };
658
659 }} // namespace cds::container
660
661 #endif // #ifndef __CDS_CONTAINER_SPLIT_LIST_MAP_RCU_H