2 This file is a part of libcds - Concurrent Data Structures library
4 (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
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_INTRUSIVE_MICHAEL_SET_NOGC_H
32 #define CDSLIB_INTRUSIVE_MICHAEL_SET_NOGC_H
34 #include <cds/intrusive/details/michael_set_base.h>
35 #include <cds/gc/nogc.h>
37 namespace cds { namespace intrusive {
39 /// Michael's hash set (template specialization for gc::nogc)
40 /** @ingroup cds_intrusive_map
41 \anchor cds_intrusive_MichaelHashSet_nogc
43 This specialization is so-called append-only when no item
44 reclamation may be performed. The set does not support deleting of list item.
46 See \ref cds_intrusive_MichaelHashSet_hp "MichaelHashSet" for description of template parameters.
47 The template parameter \p OrderedList should be any \p cds::gc::nogc -derived ordered list, for example,
48 \ref cds_intrusive_MichaelList_nogc "append-only MichaelList".
52 #ifdef CDS_DOXYGEN_INVOKED
53 class Traits = michael_set::traits
58 class MichaelHashSet< cds::gc::nogc, OrderedList, Traits >
61 typedef cds::gc::nogc gc; ///< Garbage collector
62 typedef OrderedList ordered_list; ///< type of ordered list used as a bucket implementation
63 typedef Traits traits; ///< Set traits
65 typedef typename ordered_list::value_type value_type; ///< type of value to be stored in the set
66 typedef typename ordered_list::key_comparator key_comparator; ///< key comparing functor
67 typedef typename ordered_list::disposer disposer; ///< Node disposer functor
68 #ifdef CDS_DOXYGEN_INVOKED
69 typedef typename ordered_list::stat stat; ///< Internal statistics
72 /// Hash functor for \p value_type and all its derivatives that you use
73 typedef typename cds::opt::v::hash_selector< typename traits::hash >::type hash;
74 typedef typename traits::item_counter item_counter; ///< Item counter type
75 typedef typename traits::allocator allocator; ///< Bucket table allocator
77 // GC and OrderedList::gc must be the same
78 static_assert(std::is_same<gc, typename ordered_list::gc>::value, "GC and OrderedList::gc must be the same");
82 typedef typename ordered_list::template select_stat_wrapper< typename ordered_list::stat > bucket_stat;
84 typedef typename ordered_list::template rebind_traits<
85 cds::opt::item_counter< cds::atomicity::empty_item_counter >
86 , cds::opt::stat< typename bucket_stat::wrapped_stat >
87 >::type internal_bucket_type;
89 typedef typename allocator::template rebind< internal_bucket_type >::other bucket_table_allocator;
94 typedef typename bucket_stat::stat stat;
99 hash m_HashFunctor; ///< Hash functor
100 const size_t m_nHashBitmask;
101 internal_bucket_type * m_Buckets; ///< bucket table
102 item_counter m_ItemCounter; ///< Item counter
103 stat m_Stat; ///< Internal statistics
108 /// Calculates hash value of \p key
109 template <typename Q>
110 size_t hash_value( Q const & key ) const
112 return m_HashFunctor( key ) & m_nHashBitmask;
115 /// Returns the bucket (ordered list) for \p key
116 template <typename Q>
117 internal_bucket_type& bucket( Q const & key )
119 return m_Buckets[ hash_value( key ) ];
124 ///@name Forward iterators
128 The forward iterator for Michael's set is based on \p OrderedList forward iterator and has some features:
129 - it has no post-increment operator
130 - it iterates items in unordered fashion
132 The iterator interface:
136 // Default constructor
140 iterator( iterator const& src );
142 // Dereference operator
143 value_type * operator ->() const;
145 // Dereference operator
146 value_type& operator *() const;
148 // Preincrement operator
149 iterator& operator ++();
151 // Assignment operator
152 iterator& operator = (iterator const& src);
154 // Equality operators
155 bool operator ==(iterator const& i ) const;
156 bool operator !=(iterator const& i ) const;
160 typedef michael_set::details::iterator< internal_bucket_type, false > iterator;
162 /// Const forward iterator
164 For iterator's features and requirements see \ref iterator
166 typedef michael_set::details::iterator< internal_bucket_type, true > const_iterator;
168 /// Returns a forward iterator addressing the first element in a set
170 For empty set \code begin() == end() \endcode
174 return iterator( m_Buckets[0].begin(), m_Buckets, m_Buckets + bucket_count());
177 /// Returns an iterator that addresses the location succeeding the last element in a set
179 Do not use the value returned by <tt>end</tt> function to access any item.
180 The returned value can be used only to control reaching the end of the set.
181 For empty set \code begin() == end() \endcode
185 return iterator( m_Buckets[bucket_count() - 1].end(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count());
188 /// Returns a forward const iterator addressing the first element in a set
189 const_iterator begin() const
193 /// Returns a forward const iterator addressing the first element in a set
194 const_iterator cbegin() const
196 return const_iterator( m_Buckets[0].cbegin(), m_Buckets, m_Buckets + bucket_count());
199 /// Returns an const iterator that addresses the location succeeding the last element in a set
200 const_iterator end() const
204 /// Returns an const iterator that addresses the location succeeding the last element in a set
205 const_iterator cend() const
207 return const_iterator( m_Buckets[bucket_count() - 1].cend(), m_Buckets + bucket_count() - 1, m_Buckets + bucket_count());
212 /// Initializes hash set
214 The Michael's hash set is an unbounded container, but its hash table is non-expandable.
215 At construction time you should pass estimated maximum item count and a load factor.
216 The load factor is average size of one bucket - a small number between 1 and 10.
217 The bucket is an ordered single-linked list, searching in the bucket has linear complexity <tt>O(nLoadFactor)</tt>.
218 The constructor defines hash table size as rounding <tt>nMaxItemCount / nLoadFactor</tt> up to nearest power of two.
221 size_t nMaxItemCount, ///< estimation of max item count in the hash set
222 size_t nLoadFactor ///< load factor: estimation of max number of items in the bucket
223 ) : m_nHashBitmask( michael_set::details::init_hash_bitmask( nMaxItemCount, nLoadFactor ))
224 , m_Buckets( bucket_table_allocator().allocate( bucket_count()))
226 for ( auto it = m_Buckets, itEnd = m_Buckets + bucket_count(); it != itEnd; ++it )
227 construct_bucket<bucket_stat>( it );
230 /// Clears hash set object and destroys it
235 for ( auto it = m_Buckets, itEnd = m_Buckets + bucket_count(); it != itEnd; ++it )
236 it->~internal_bucket_type();
237 bucket_table_allocator().deallocate( m_Buckets, bucket_count());
242 The function inserts \p val in the set if it does not contain
243 an item with key equal to \p val.
245 Returns \p true if \p val is placed into the set, \p false otherwise.
247 bool insert( value_type& val )
249 bool bRet = bucket( val ).insert( val );
255 /// Updates the element
257 The operation performs inserting or changing data with lock-free manner.
259 If the item \p val not found in the set, then \p val is inserted iff \p bAllowInsert is \p true.
260 Otherwise, the functor \p func is called with item found.
261 The functor signature is:
264 void operator()( bool bNew, value_type& item, value_type& val );
268 - \p bNew - \p true if the item has been inserted, \p false otherwise
269 - \p item - item of the set
270 - \p val - argument \p val passed into the \p %update() function
271 If new item has been inserted (i.e. \p bNew is \p true) then \p item and \p val arguments
272 refers to the same thing.
274 The functor may change non-key fields of the \p item.
276 Returns <tt> std::pair<bool, bool> </tt> where \p first is \p true if operation is successful,
277 \p second is \p true if new item has been added or \p false if the item with \p key
278 already is in the set.
280 @warning For \ref cds_intrusive_MichaelList_hp "MichaelList" as the bucket see \ref cds_intrusive_item_creating "insert item troubleshooting".
281 \ref cds_intrusive_LazyList_hp "LazyList" provides exclusive access to inserted item and does not require any node-level
284 template <typename Func>
285 std::pair<bool, bool> update( value_type& val, Func func, bool bAllowInsert = true )
287 std::pair<bool, bool> bRet = bucket( val ).update( val, func, bAllowInsert );
293 template <typename Func>
294 CDS_DEPRECATED("ensure() is deprecated, use update()")
295 std::pair<bool, bool> ensure( value_type& val, Func func )
297 return update( val, func, true );
301 /// Checks whether the set contains \p key
304 The function searches the item with key equal to \p key
305 and returns the pointer to an element found or \p nullptr.
307 Note the hash functor specified for class \p Traits template parameter
308 should accept a parameter of type \p Q that can be not the same as \p value_type.
310 template <typename Q>
311 value_type * contains( Q const& key )
313 return bucket( key ).contains( key );
316 template <typename Q>
317 CDS_DEPRECATED("use contains()")
318 value_type * find( Q const& key )
320 return contains( key );
324 /// Checks whether the set contains \p key using \p pred predicate for searching
326 The function is an analog of <tt>contains( key )</tt> but \p pred is used for key comparing.
327 \p Less functor has the interface like \p std::less.
328 \p Less must imply the same element order as the comparator used for building the set.
330 template <typename Q, typename Less>
331 value_type * contains( Q const& key, Less pred )
333 return bucket( key ).contains( key, pred );
336 template <typename Q, typename Less>
337 CDS_DEPRECATED("use contains()")
338 value_type * find_with( Q const& key, Less pred )
340 return contains( key, pred );
344 /// Finds the key \p key
345 /** \anchor cds_intrusive_MichaelHashSet_nogc_find_func
346 The function searches the item with key equal to \p key and calls the functor \p f for item found.
347 The interface of \p Func functor is:
350 void operator()( value_type& item, Q& key );
353 where \p item is the item found, \p key is the <tt>find</tt> function argument.
355 The functor can change non-key fields of \p item.
356 The functor does not serialize simultaneous access to the set \p item. If such access is
357 possible you must provide your own synchronization schema on item level to exclude unsafe item modifications.
359 The \p key argument is non-const since it can be used as \p f functor destination i.e., the functor
360 can modify both arguments.
362 Note the hash functor specified for class \p Traits template parameter
363 should accept a parameter of type \p Q that can be not the same as \p value_type.
365 The function returns \p true if \p key is found, \p false otherwise.
367 template <typename Q, typename Func>
368 bool find( Q& key, Func f )
370 return bucket( key ).find( key, f );
373 template <typename Q, typename Func>
374 bool find( Q const& key, Func f )
376 return bucket( key ).find( key, f );
380 /// Finds the key \p key using \p pred predicate for searching
382 The function is an analog of \ref cds_intrusive_MichaelHashSet_nogc_find_func "find(Q&, Func)"
383 but \p pred is used for key comparing.
384 \p Less functor has the interface like \p std::less.
385 \p pred must imply the same element order as the comparator used for building the set.
387 template <typename Q, typename Less, typename Func>
388 bool find_with( Q& key, Less pred, Func f )
390 return bucket( key ).find_with( key, pred, f );
393 template <typename Q, typename Less, typename Func>
394 bool find_with( Q const& key, Less pred, Func f )
396 return bucket( key ).find_with( key, pred, f );
400 /// Clears the set (non-atomic)
402 The function unlink all items from the set.
403 The function is not atomic. It cleans up each bucket and then resets the item counter to zero.
404 If there are a thread that performs insertion while \p %clear() is working the result is undefined in general case:
405 <tt> empty() </tt> may return \p true but the set may contain item(s).
406 Therefore, \p %clear() may be used only for debugging purposes.
408 For each item the \p disposer is called after unlinking.
412 for ( size_t i = 0; i < bucket_count(); ++i )
413 m_Buckets[i].clear();
414 m_ItemCounter.reset();
418 /// Checks if the set is empty
420 @warning If you use \p atomicity::empty_item_counter in \p traits::item_counter,
421 the function always returns \p true.
428 /// Returns item count in the set
430 If you use \p atomicity::empty_item_counter in \p traits::item_counter,
431 the function always returns 0.
435 return m_ItemCounter;
438 /// Returns the size of hash table
440 Since \p %MichaelHashSet cannot dynamically extend the hash table size,
441 the value returned is an constant depending on object initialization parameters;
442 see MichaelHashSet::MichaelHashSet for explanation.
444 size_t bucket_count() const
446 return m_nHashBitmask + 1;
449 /// Returns const reference to internal statistics
450 stat const& statistics() const
457 template <typename Stat>
458 typename std::enable_if< Stat::empty >::type construct_bucket( internal_bucket_type * b )
460 new (b) internal_bucket_type;
463 template <typename Stat>
464 typename std::enable_if< !Stat::empty >::type construct_bucket( internal_bucket_type * b )
466 new (b) internal_bucket_type( m_Stat );
471 }} // namespace cds::intrusive
473 #endif // #ifndef CDSLIB_INTRUSIVE_MICHAEL_SET_NOGC_H