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