add find(Q const&, Func), find_with(Q const&, Pred, Func) to all sets
[libcds.git] / cds / container / michael_set_rcu.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_MICHAEL_SET_RCU_H
4 #define __CDS_CONTAINER_MICHAEL_SET_RCU_H
5
6 #include <cds/container/details/michael_set_base.h>
7 #include <cds/details/allocator.h>
8
9 namespace cds { namespace container {
10
11     /// Michael's hash set (template specialization for \ref cds_urcu_desc "RCU")
12     /** @ingroup cds_nonintrusive_set
13         \anchor cds_nonintrusive_MichaelHashSet_rcu
14
15         Source:
16             - [2002] Maged Michael "High performance dynamic lock-free hash tables and list-based sets"
17
18         Michael's hash table algorithm is based on lock-free ordered list and it is very simple.
19         The main structure is an array \p T of size \p M. Each element in \p T is basically a pointer
20         to a hash bucket, implemented as a singly linked list. The array of buckets cannot be dynamically expanded.
21         However, each bucket may contain unbounded number of items.
22
23         Template parameters are:
24         - \p RCU - one of \ref cds_urcu_gc "RCU type"
25         - \p OrderedList - ordered list implementation used as the bucket for hash set, for example,
26             \ref cds_nonintrusive_MichaelList_rcu "MichaelList".
27             The ordered list implementation specifies the type \p T stored in the hash-set,
28             the comparison functor for the type \p T and other features specific for
29             the ordered list.
30         - \p Traits - set traits, default is michael_set::traits.
31             Instead of defining \p Traits struct you may use option-based syntax with michael_set::make_traits metafunction.
32
33         About hash functor see \ref cds_nonintrusive_MichaelHashSet_hash_functor "MichaelSet hash functor".
34
35         <b>How to use</b>
36
37         Suppose, we have the following type \p Foo that we want to store in your \p %MichaelHashSet:
38         \code
39         struct Foo {
40             int     nKey    ;   // key field
41             int     nVal    ;   // value field
42         };
43         \endcode
44
45         To use \p %MichaelHashSet for \p Foo values, you should first choose suitable ordered list class
46         that will be used as a bucket for the set. We will cds::urcu::general_buffered<> RCU type and
47         MichaelList as a bucket type.
48         You should include RCU-related header file (<tt>cds/urcu/general_buffered.h</tt> in this example)
49         before including <tt>cds/container/michael_set_rcu.h</tt>.
50         Also, for ordered list we should develop a comparator for our \p Foo struct.
51         \code
52         #include <cds/urcu/general_buffered.h>
53         #include <cds/container/michael_list_rcu.h>
54         #include <cds/container/michael_set_rcu.h>
55
56         namespace cc = cds::container;
57
58         // Foo comparator
59         struct Foo_cmp {
60             int operator ()(Foo const& v1, Foo const& v2 ) const
61             {
62                 if ( std::less( v1.nKey, v2.nKey ))
63                     return -1;
64                 return std::less(v2.nKey, v1.nKey) ? 1 : 0;
65             }
66         };
67
68         // Ordered list
69         typedef cc::MichaelList< cds::urcu::gc< cds::urcu::general_buffered<> >, Foo,
70             typename cc::michael_list::make_traits<
71                 cc::opt::compare< Foo_cmp >     // item comparator option
72             >::type
73         > bucket_list;
74
75         // Hash functor for Foo
76         struct foo_hash {
77             size_t operator ()( int i ) const
78             {
79                 return std::hash( i );
80             }
81             size_t operator()( Foo const& i ) const
82             {
83                 return std::hash( i.nKey );
84             }
85         };
86
87         // Declare the set
88         // Note that \p RCU template parameter of ordered list must be equal \p RCU for the set.
89         typedef cc::MichaelHashSet< cds::urcu::gc< cds::urcu::general_buffered<> >, bucket_list,
90             cc::michael_set::make_traits<
91                 cc::opt::hash< foo_hash >
92             >::type
93         > foo_set;
94
95         foo_set fooSet;
96         \endcode
97     */
98     template <
99         class RCU,
100         class OrderedList,
101 #ifdef CDS_DOXYGEN_INVOKED
102         class Traits = michael_set::traits
103 #else
104         class Traits
105 #endif
106     >
107     class MichaelHashSet< cds::urcu::gc< RCU >, OrderedList, Traits >
108     {
109     public:
110         typedef cds::urcu::gc< RCU > gc; ///< RCU used as garbage collector
111         typedef OrderedList bucket_type; ///< type of ordered list to be used as a bucket implementation
112         typedef Traits      traits;      ///< Set traits
113
114         typedef typename bucket_type::value_type        value_type;     ///< type of value to be stored in the list
115         typedef typename bucket_type::key_comparator    key_comparator; ///< key comparing functor
116
117         /// Hash functor for \ref value_type and all its derivatives that you use
118         typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
119         typedef typename traits::item_counter item_counter;   ///< Item counter type
120
121         /// Bucket table allocator
122         typedef cds::details::Allocator< bucket_type, typename traits::allocator >  bucket_table_allocator;
123
124         typedef typename bucket_type::rcu_lock   rcu_lock;   ///< RCU scoped lock
125         typedef typename bucket_type::exempt_ptr exempt_ptr; ///< pointer to extracted node
126         /// Group of \p extract_xxx functions require external locking if underlying ordered list requires that
127         static CDS_CONSTEXPR const bool c_bExtractLockExternal = bucket_type::c_bExtractLockExternal;
128
129     protected:
130         item_counter    m_ItemCounter; ///< Item counter
131         hash            m_HashFunctor; ///< Hash functor
132         bucket_type *   m_Buckets;     ///< bucket table
133
134     private:
135         //@cond
136         const size_t    m_nHashBitmask;
137         //@endcond
138
139     protected:
140         //@cond
141         /// Calculates hash value of \p key
142         template <typename Q>
143         size_t hash_value( Q const& key ) const
144         {
145             return m_HashFunctor( key ) & m_nHashBitmask;
146         }
147
148         /// Returns the bucket (ordered list) for \p key
149         template <typename Q>
150         bucket_type&    bucket( Q const& key )
151         {
152             return m_Buckets[ hash_value( key ) ];
153         }
154         template <typename Q>
155         bucket_type const&    bucket( Q const& key ) const
156         {
157             return m_Buckets[ hash_value( key ) ];
158         }
159         //@endcond
160     public:
161         /// Forward iterator
162         /**
163             The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
164             - it has no post-increment operator
165             - it iterates items in unordered fashion
166             - The iterator cannot be moved across thread boundary since it may contain GC's guard that is thread-private GC data.
167             - Iterator ensures thread-safety even if you delete the item that iterator points to. However, in case of concurrent
168               deleting operations it is no guarantee that you iterate all item in the set.
169
170             Therefore, the use of iterators in concurrent environment is not good idea. Use the iterator for the concurrent container
171             for debug purpose only.
172         */
173         typedef michael_set::details::iterator< bucket_type, false >    iterator;
174
175         /// Const forward iterator
176         typedef michael_set::details::iterator< bucket_type, true >     const_iterator;
177
178         /// Returns a forward iterator addressing the first element in a set
179         /**
180             For empty set \code begin() == end() \endcode
181         */
182         iterator begin()
183         {
184             return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count() );
185         }
186
187         /// Returns an iterator that addresses the location succeeding the last element in a set
188         /**
189             Do not use the value returned by <tt>end</tt> function to access any item.
190             The returned value can be used only to control reaching the end of the set.
191             For empty set \code begin() == end() \endcode
192         */
193         iterator end()
194         {
195             return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
196         }
197
198         /// Returns a forward const iterator addressing the first element in a set
199         //@{
200         const_iterator begin() const
201         {
202             return get_const_begin();
203         }
204         const_iterator cbegin() const
205         {
206             return get_const_begin();
207         }
208         //@}
209
210         /// Returns an const iterator that addresses the location succeeding the last element in a set
211         //@{
212         const_iterator end() const
213         {
214             return get_const_end();
215         }
216         const_iterator cend() const
217         {
218             return get_const_end();
219         }
220         //@}
221
222     private:
223         //@cond
224         const_iterator get_const_begin() const
225         {
226             return const_iterator( const_cast<bucket_type const&>(m_Buckets[0]).begin(), m_Buckets, m_Buckets + bucket_count() );
227         }
228         const_iterator get_const_end() const
229         {
230             return const_iterator( const_cast<bucket_type const&>(m_Buckets[bucket_count() - 1]).end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count() );
231         }
232         //@endcond
233
234     public:
235         /// Initialize hash set
236         /** @copydetails cds_nonintrusive_MichaelHashSet_hp_ctor
237         */
238         MichaelHashSet(
239             size_t nMaxItemCount,   ///< estimation of max item count in the hash set
240             size_t nLoadFactor      ///< load factor: estimation of max number of items in the bucket
241         ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
242         {
243             // GC and OrderedList::gc must be the same
244             static_assert( std::is_same<gc, typename bucket_type::gc>::value, "GC and OrderedList::gc must be the same");
245
246             // atomicity::empty_item_counter is not allowed as a item counter
247             static_assert( !std::is_same<item_counter, atomicity::empty_item_counter>::value,
248                            "atomicity::empty_item_counter is not allowed as a item counter");
249
250             m_Buckets = bucket_table_allocator().NewArray( bucket_count() );
251         }
252
253         /// Clears hash set and destroys it
254         ~MichaelHashSet()
255         {
256             clear();
257             bucket_table_allocator().Delete( m_Buckets, bucket_count() );
258         }
259
260         /// Inserts new node
261         /**
262             The function creates a node with copy of \p val value
263             and then inserts the node created into the set.
264
265             The type \p Q should contain as minimum the complete key for the node.
266             The object of \ref value_type should be constructible from a value of type \p Q.
267             In trivial case, \p Q is equal to \ref value_type.
268
269             The function applies RCU lock internally.
270
271             Returns \p true if \p val is inserted into the set, \p false otherwise.
272         */
273         template <typename Q>
274         bool insert( Q const& val )
275         {
276             const bool bRet = bucket( val ).insert( val );
277             if ( bRet )
278                 ++m_ItemCounter;
279             return bRet;
280         }
281
282         /// Inserts new node
283         /**
284             The function allows to split creating of new item into two part:
285             - create item with key only
286             - insert new item into the set
287             - if inserting is success, calls  \p f functor to initialize value-fields of \p val.
288
289             The functor signature is:
290             \code
291                 void func( value_type& val );
292             \endcode
293             where \p val is the item inserted.
294             The user-defined functor is called only if the inserting is success.
295
296             The function applies RCU lock internally.
297
298             @warning For \ref cds_nonintrusive_MichaelList_rcu "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
299             \ref cds_nonintrusive_LazyList_rcu "LazyList" provides exclusive access to inserted item and does not require any node-level
300             synchronization.
301             */
302         template <typename Q, typename Func>
303         bool insert( Q const& val, Func f )
304         {
305             const bool bRet = bucket( val ).insert( val, f );
306             if ( bRet )
307                 ++m_ItemCounter;
308             return bRet;
309         }
310
311         /// Ensures that the item exists in the set
312         /**
313             The operation performs inserting or changing data with lock-free manner.
314
315             If the \p val key not found in the set, then the new item created from \p val
316             is inserted into the set. Otherwise, the functor \p func is called with the item found.
317             The functor \p Func signature is:
318             \code
319                 struct my_functor {
320                     void operator()( bool bNew, value_type& item, const Q& val );
321                 };
322             \endcode
323
324             with arguments:
325             - \p bNew - \p true if the item has been inserted, \p false otherwise
326             - \p item - item of the set
327             - \p val - argument \p key passed into the \p ensure function
328
329             The functor may change non-key fields of the \p item.
330
331             The function applies RCU lock internally.
332
333             Returns <tt> std::pair<bool, bool> </tt> where \p first is true if operation is successfull,
334             \p second is true if new item has been added or \p false if the item with \p key
335             already is in the set.
336
337             @warning For \ref cds_nonintrusive_MichaelList_rcu "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
338             \ref cds_nonintrusive_LazyList_rcu "LazyList" provides exclusive access to inserted item and does not require any node-level
339             synchronization.
340         */
341         template <typename Q, typename Func>
342         std::pair<bool, bool> ensure( const Q& val, Func func )
343         {
344             std::pair<bool, bool> bRet = bucket( val ).ensure( val, func );
345             if ( bRet.first && bRet.second )
346                 ++m_ItemCounter;
347             return bRet;
348         }
349
350         /// Inserts data of type \p value_type created from \p args
351         /**
352             Returns \p true if inserting successful, \p false otherwise.
353
354             The function applies RCU lock internally.
355         */
356         template <typename... Args>
357         bool emplace( Args&&... args )
358         {
359             bool bRet = bucket( value_type(std::forward<Args>(args)...) ).emplace( std::forward<Args>(args)... );
360             if ( bRet )
361                 ++m_ItemCounter;
362             return bRet;
363         }
364
365         /// Deletes \p key from the set
366         /** \anchor cds_nonintrusive_MichealSet_rcu_erase_val
367
368             Since the key of MichaelHashSet's item type \p value_type is not explicitly specified,
369             template parameter \p Q defines the key type searching in the list.
370             The set item comparator should be able to compare the type \p value_type
371             and the type \p Q.
372
373             RCU \p synchronize method can be called. RCU should not be locked.
374
375             Return \p true if key is found and deleted, \p false otherwise
376         */
377         template <typename Q>
378         bool erase( Q const& key )
379         {
380             const bool bRet = bucket( key ).erase( key );
381             if ( bRet )
382                 --m_ItemCounter;
383             return bRet;
384         }
385
386         /// Deletes the item from the set using \p pred predicate for searching
387         /**
388             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_erase_val "erase(Q const&)"
389             but \p pred is used for key comparing.
390             \p Less functor has the interface like \p std::less.
391             \p Less must imply the same element order as the comparator used for building the set.
392         */
393         template <typename Q, typename Less>
394         bool erase_with( Q const& key, Less pred )
395         {
396             const bool bRet = bucket( key ).erase_with( key, pred );
397             if ( bRet )
398                 --m_ItemCounter;
399             return bRet;
400         }
401
402         /// Deletes \p key from the set
403         /** \anchor cds_nonintrusive_MichealSet_rcu_erase_func
404
405             The function searches an item with key \p key, calls \p f functor
406             and deletes the item. If \p key is not found, the functor is not called.
407
408             The functor \p Func interface:
409             \code
410             struct extractor {
411                 void operator()(value_type const& val);
412             };
413             \endcode
414
415             Since the key of %MichaelHashSet's \p value_type is not explicitly specified,
416             template parameter \p Q defines the key type searching in the list.
417             The list item comparator should be able to compare the type \p T of list item
418             and the type \p Q.
419
420             RCU \p synchronize method can be called. RCU should not be locked.
421
422             Return \p true if key is found and deleted, \p false otherwise
423         */
424         template <typename Q, typename Func>
425         bool erase( Q const& key, Func f )
426         {
427             const bool bRet = bucket( key ).erase( key, f );
428             if ( bRet )
429                 --m_ItemCounter;
430             return bRet;
431         }
432
433         /// Deletes the item from the set using \p pred predicate for searching
434         /**
435             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_erase_func "erase(Q const&, Func)"
436             but \p pred is used for key comparing.
437             \p Less functor has the interface like \p std::less.
438             \p Less must imply the same element order as the comparator used for building the set.
439         */
440         template <typename Q, typename Less, typename Func>
441         bool erase_with( Q const& key, Less pred, Func f )
442         {
443             const bool bRet = bucket( key ).erase_with( key, pred, f );
444             if ( bRet )
445                 --m_ItemCounter;
446             return bRet;
447         }
448
449         /// Extracts an item from the set
450         /** \anchor cds_nonintrusive_MichaelHashSet_rcu_extract
451             The function searches an item with key equal to \p key in the set,
452             unlinks it from the set, and returns \ref cds::urcu::exempt_ptr "exempt_ptr" pointer to the item found.
453             If the item with the key equal to \p key is not found the function return an empty \p exempt_ptr.
454
455             @note The function does NOT call RCU read-side lock or synchronization,
456             and does NOT dispose the item found. It just excludes the item from the set
457             and returns a pointer to item found.
458             You should lock RCU before calling of the function, and you should synchronize RCU
459             outside the RCU lock to free extracted item
460
461             \code
462             #include <cds/urcu/general_buffered.h>
463             #include <cds/container/michael_list_rcu.h>
464             #include <cds/container/michael_set_rcu.h>
465
466             typedef cds::urcu::gc< general_buffered<> > rcu;
467             typedef cds::container::MichaelList< rcu, Foo > rcu_michael_list;
468             typedef cds::container::MichaelHashSet< rcu, rcu_michael_list, foo_traits > rcu_michael_set;
469
470             rcu_michael_set theSet;
471             // ...
472
473             rcu_michael_set::exempt_ptr p;
474             {
475                 // first, we should lock RCU
476                 rcu_michael_set::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                 p = theSet.extract( 10 );
481                 if ( p ) {
482                     // do something with p
483                     ...
484                 }
485             }
486
487             // We may safely release p here
488             // release() passes the pointer to RCU reclamation cycle
489             p.release();
490             \endcode
491         */
492         template <typename Q>
493         exempt_ptr extract( Q const& key )
494         {
495             exempt_ptr p = bucket( key ).extract( key );
496             if ( p )
497                 --m_ItemCounter;
498             return p;
499         }
500
501         /// Extracts an item from the set using \p pred predicate for searching
502         /**
503             The function is an analog of \ref cds_nonintrusive_MichaelHashSet_rcu_extract "extract(exempt_ptr&, Q const&)"
504             but \p pred is used for key comparing.
505             \p Less functor has the interface like \p std::less.
506             \p pred must imply the same element order as the comparator used for building the set.
507         */
508         template <typename Q, typename Less>
509         exempt_ptr extract_with( Q const& key, Less pred )
510         {
511             exempt_ptr p = bucket( key ).extract_with( key, pred );
512             if ( p )
513                 --m_ItemCounter;
514             return p;
515         }
516
517         /// Finds the key \p key
518         /** \anchor cds_nonintrusive_MichealSet_rcu_find_func
519
520             The function searches the item with key equal to \p key and calls the functor \p f for item found.
521             The interface of \p Func functor is:
522             \code
523             struct functor {
524                 void operator()( value_type& item, Q& key );
525             };
526             \endcode
527             where \p item is the item found, \p key is the <tt>find</tt> function argument.
528
529             The functor may change non-key fields of \p item. Note that the functor is only guarantee
530             that \p item cannot be disposed during functor is executing.
531             The functor does not serialize simultaneous access to the set's \p item. If such access is
532             possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
533
534             The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
535             can modify both arguments.
536
537             Note the hash functor specified for class \p Traits template parameter
538             should accept a parameter of type \p Q that may be not the same as \p value_type.
539
540             The function applies RCU lock internally.
541
542             The function returns \p true if \p key is found, \p false otherwise.
543         */
544         template <typename Q, typename Func>
545         bool find( Q& key, Func f ) const
546         {
547             return bucket( key ).find( key, f );
548         }
549         //@cond
550         template <typename Q, typename Func>
551         bool find( Q const& key, Func f ) const
552         {
553             return bucket( key ).find( key, f );
554         }
555         //@endcond
556
557         /// Finds the key \p key using \p pred predicate for searching
558         /**
559             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_find_func "find(Q&, Func)"
560             but \p pred is used for key comparing.
561             \p Less functor has the interface like \p std::less.
562             \p Less must imply the same element order as the comparator used for building the set.
563         */
564         template <typename Q, typename Less, typename Func>
565         bool find_with( Q& key, Less pred, Func f ) const
566         {
567             return bucket( key ).find_with( key, pred, f );
568         }
569         //@cond
570         template <typename Q, typename Less, typename Func>
571         bool find_with( Q const& key, Less pred, Func f ) const
572         {
573             return bucket( key ).find_with( key, pred, f );
574         }
575         //@endcond
576
577         /// Finds the key \p key
578         /** \anchor cds_nonintrusive_MichealSet_rcu_find_val
579
580             The function searches the item with key equal to \p key
581             and returns \p true if it is found, and \p false otherwise.
582
583             Note the hash functor specified for class \p Traits template parameter
584             should accept a parameter of type \p Q that may be not the same as \p value_type.
585         */
586         template <typename Q>
587         bool find( Q const & key ) const
588         {
589             return bucket( key ).find( key );
590         }
591
592         /// Finds the key \p key using \p pred predicate for searching
593         /**
594             The function is an analog of \ref cds_nonintrusive_MichealSet_rcu_find_val "find(Q const&)"
595             but \p pred is used for key comparing.
596             \p Less functor has the interface like \p std::less.
597             \p Less must imply the same element order as the comparator used for building the set.
598         */
599         template <typename Q, typename Less>
600         bool find_with( Q const & key, Less pred ) const
601         {
602             return bucket( key ).find_with( key, pred );
603         }
604
605         /// Finds the key \p key and return the item found
606         /** \anchor cds_nonintrusive_MichaelHashSet_rcu_get
607             The function searches the item with key equal to \p key and returns the pointer to item found.
608             If \p key is not found it returns \p nullptr.
609
610             Note the compare functor should accept a parameter of type \p Q that can be not the same as \p value_type.
611
612             RCU should be locked before call of this function.
613             Returned item is valid only while RCU is locked:
614             \code
615             typedef cds::container::MichaelHashSet< your_template_parameters > hash_set;
616             hash_set theSet;
617             // ...
618             {
619                 // Lock RCU
620                 hash_set::rcu_lock lock;
621
622                 foo * pVal = theSet.get( 5 );
623                 if ( pVal ) {
624                     // Deal with pVal
625                     //...
626                 }
627                 // Unlock RCU by rcu_lock destructor
628                 // pVal can be freed at any time after RCU has been unlocked
629             }
630             \endcode
631         */
632         template <typename Q>
633         value_type * get( Q const& key ) const
634         {
635             return bucket( key ).get( key );
636         }
637
638         /// Finds the key \p key and return the item found
639         /**
640             The function is an analog of \ref cds_nonintrusive_MichaelHashSet_rcu_get "get(Q const&)"
641             but \p pred is used for comparing the keys.
642
643             \p Less functor has the semantics like \p std::less but should take arguments of type \ref value_type and \p Q
644             in any order.
645             \p pred must imply the same element order as the comparator used for building the set.
646         */
647         template <typename Q, typename Less>
648         value_type * get_with( Q const& key, Less pred ) const
649         {
650             return bucket( key ).get_with( key, pred );
651         }
652
653         /// Clears the set (not atomic)
654         void clear()
655         {
656             for ( size_t i = 0; i < bucket_count(); ++i )
657                 m_Buckets[i].clear();
658             m_ItemCounter.reset();
659         }
660
661         /// Checks if the set is empty
662         /**
663             Emptiness is checked by item counting: if item count is zero then the set is empty.
664             Thus, the correct item counting feature is an important part of Michael's set implementation.
665         */
666         bool empty() const
667         {
668             return size() == 0;
669         }
670
671         /// Returns item count in the set
672         size_t size() const
673         {
674             return m_ItemCounter;
675         }
676
677         /// Returns the size of hash table
678         /**
679             Since \p %MichaelHashSet cannot dynamically extend the hash table size,
680             the value returned is an constant depending on object initialization parameters;
681             see MichaelHashSet::MichaelHashSet for explanation.
682         */
683         size_t bucket_count() const
684         {
685             return m_nHashBitmask + 1;
686         }
687     };
688
689 }} // namespace cds::container
690
691 #endif // ifndef __CDS_CONTAINER_MICHAEL_SET_RCU_H