3 #ifndef CDSLIB_GC_IMPL_HP_DECL_H
4 #define CDSLIB_GC_IMPL_HP_DECL_H
6 #include <stdexcept> // overflow_error
7 #include <cds/gc/details/hp.h>
8 #include <cds/details/marked_ptr.h>
10 namespace cds { namespace gc {
11 /// @defgroup cds_garbage_collector Garbage collectors
13 /// Hazard Pointer garbage collector
14 /** @ingroup cds_garbage_collector
15 @headerfile cds/gc/hp.h
17 Implementation of classic Hazard Pointer garbage collector.
20 - [2002] Maged M.Michael "Safe memory reclamation for dynamic lock-freeobjects using atomic reads and writes"
21 - [2003] Maged M.Michael "Hazard Pointers: Safe memory reclamation for lock-free objects"
22 - [2004] Andrei Alexandrescy, Maged Michael "Lock-free Data Structures with Hazard Pointers"
24 Hazard Pointer garbage collector is a singleton. The main user-level part of Hazard Pointer schema is
25 GC class \p %cds::gc::HP and its nested classes. Before use any HP-related class you must initialize HP garbage collector
26 by contructing \p %cds::gc::HP object in beginning of your \p main().
27 See \ref cds_how_to_use "How to use" section for details how to apply garbage collector.
32 /// Native guarded pointer type
34 @headerfile cds/gc/hp.h
36 typedef gc::hp::hazard_pointer guarded_pointer;
40 @headerfile cds/gc/hp.h
42 template <typename T> using atomic_ref = atomics::atomic<T *>;
44 /// Atomic marked pointer
46 @headerfile cds/gc/hp.h
48 template <typename MarkedPtr> using atomic_marked_ptr = atomics::atomic<MarkedPtr>;
52 @headerfile cds/gc/hp.h
54 template <typename T> using atomic_type = atomics::atomic<T>;
56 /// Thread GC implementation for internal usage
58 @headerfile cds/gc/hp.h
60 typedef hp::ThreadGC thread_gc_impl;
62 /// Wrapper for hp::ThreadGC class
64 @headerfile cds/gc/hp.h
65 This class performs automatically attaching/detaching Hazard Pointer GC
66 for the current thread.
68 class thread_gc: public thread_gc_impl
77 The constructor attaches the current thread to the Hazard Pointer GC
78 if it is not yet attached.
79 The \p bPersistent parameter specifies attachment persistence:
80 - \p true - the class destructor will not detach the thread from Hazard Pointer GC.
81 - \p false (default) - the class destructor will detach the thread from Hazard Pointer GC.
84 bool bPersistent = false
85 ) ; //inline in hp_impl.h
89 If the object has been created in persistent mode, the destructor does nothing.
90 Otherwise it detaches the current thread from Hazard Pointer GC.
92 ~thread_gc() ; // inline in hp_impl.h
94 public: // for internal use only!!!
96 static cds::gc::hp::details::hp_guard& alloc_guard(); // inline in hp_impl.h
97 static void free_guard( cds::gc::hp::details::hp_guard& g ); // inline in hp_impl.h
101 /// Hazard Pointer guard
103 @headerfile cds/gc/hp.h
105 A guard is the hazard pointer.
106 Additionally, the \p %Guard class manages allocation and deallocation of the hazard pointer
108 A \p %Guard object is not copy- and move-constructible
109 and not copy- and move-assignable.
111 class Guard : public hp::guard
114 typedef hp::guard base_class;
123 Guard( Guard const& ) = delete;
124 Guard( Guard&& s ) = delete;
125 Guard& operator=(Guard const&) = delete;
126 Guard& operator=(Guard&&) = delete;
129 /// Protects a pointer of type \p atomic<T*>
131 Return the value of \p toGuard
133 The function tries to load \p toGuard and to store it
134 to the HP slot repeatedly until the guard's value equals \p toGuard
136 template <typename T>
137 T protect( atomics::atomic<T> const& toGuard )
139 T pCur = toGuard.load(atomics::memory_order_acquire);
142 pRet = assign( pCur );
143 pCur = toGuard.load(atomics::memory_order_acquire);
144 } while ( pRet != pCur );
148 /// Protects a converted pointer of type \p atomic<T*>
150 Return the value of \p toGuard
152 The function tries to load \p toGuard and to store result of \p f functor
153 to the HP slot repeatedly until the guard's value equals \p toGuard.
155 The function is useful for intrusive containers when \p toGuard is a node pointer
156 that should be converted to a pointer to the value before protecting.
157 The parameter \p f of type Func is a functor that makes this conversion:
160 value_type * operator()( T * p );
163 Really, the result of <tt> f( toGuard.load() ) </tt> is assigned to the hazard pointer.
165 template <typename T, class Func>
166 T protect( atomics::atomic<T> const& toGuard, Func f )
168 T pCur = toGuard.load(atomics::memory_order_acquire);
173 pCur = toGuard.load(atomics::memory_order_acquire);
174 } while ( pRet != pCur );
178 /// Store \p p to the guard
180 The function equals to a simple assignment the value \p p to guard, no loop is performed.
181 Can be used for a pointer that cannot be changed concurrently
183 template <typename T>
186 return base_class::operator =(p);
190 std::nullptr_t assign( std::nullptr_t )
192 return base_class::operator =(nullptr);
196 /// Copy from \p src guard to \p this guard
197 void copy( Guard const& src )
199 assign( src.get_native() );
202 /// Store marked pointer \p p to the guard
204 The function equals to a simple assignment of <tt>p.ptr()</tt>, no loop is performed.
205 Can be used for a marked pointer that cannot be changed concurrently.
207 template <typename T, int BITMASK>
208 T * assign( cds::details::marked_ptr<T, BITMASK> p )
210 return base_class::operator =( p.ptr() );
213 /// Clear value of the guard
219 /// Get the value currently protected
220 template <typename T>
223 return reinterpret_cast<T *>( get_native() );
226 /// Get native hazard pointer stored
227 guarded_pointer get_native() const
229 return base_class::get();
233 /// Array of Hazard Pointer guards
235 @headerfile cds/gc/hp.h
236 The class is intended for allocating an array of hazard pointer guards.
237 Template parameter \p Count defines the size of the array.
239 A \p %GuardArray object is not copy- and move-constructible
240 and not copy- and move-assignable.
242 template <size_t Count>
243 class GuardArray : public hp::array<Count>
246 typedef hp::array<Count> base_class;
249 /// Rebind array for other size \p Count2
250 template <size_t Count2>
252 typedef GuardArray<Count2> other ; ///< rebinding result
261 GuardArray( GuardArray const& ) = delete;
262 GuardArray( GuardArray&& ) = delete;
263 GuardArray& operator=(GuardArray const&) = delete;
264 GuardArray& operator-(GuardArray&&) = delete;
267 /// Protects a pointer of type \p atomic<T*>
269 Return the value of \p toGuard
271 The function tries to load \p toGuard and to store it
272 to the slot \p nIndex repeatedly until the guard's value equals \p toGuard
274 template <typename T>
275 T protect( size_t nIndex, atomics::atomic<T> const& toGuard )
279 pRet = assign( nIndex, toGuard.load(atomics::memory_order_acquire) );
280 } while ( pRet != toGuard.load(atomics::memory_order_relaxed));
285 /// Protects a pointer of type \p atomic<T*>
287 Return the value of \p toGuard
289 The function tries to load \p toGuard and to store it
290 to the slot \p nIndex repeatedly until the guard's value equals \p toGuard
292 The function is useful for intrusive containers when \p toGuard is a node pointer
293 that should be converted to a pointer to the value type before guarding.
294 The parameter \p f of type Func is a functor that makes this conversion:
297 value_type * operator()( T * p );
300 Really, the result of <tt> f( toGuard.load() ) </tt> is assigned to the hazard pointer.
302 template <typename T, class Func>
303 T protect( size_t nIndex, atomics::atomic<T> const& toGuard, Func f )
307 assign( nIndex, f( pRet = toGuard.load(atomics::memory_order_acquire) ));
308 } while ( pRet != toGuard.load(atomics::memory_order_relaxed));
313 /// Store \p to the slot \p nIndex
315 The function equals to a simple assignment, no loop is performed.
317 template <typename T>
318 T * assign( size_t nIndex, T * p )
320 base_class::set(nIndex, p);
324 /// Store marked pointer \p p to the guard
326 The function equals to a simple assignment of <tt>p.ptr()</tt>, no loop is performed.
327 Can be used for a marked pointer that cannot be changed concurrently.
329 template <typename T, int BITMASK>
330 T * assign( size_t nIndex, cds::details::marked_ptr<T, BITMASK> p )
332 return assign( nIndex, p.ptr() );
335 /// Copy guarded value from \p src guard to slot at index \p nIndex
336 void copy( size_t nIndex, Guard const& src )
338 assign( nIndex, src.get_native() );
341 /// Copy guarded value from slot \p nSrcIndex to slot at index \p nDestIndex
342 void copy( size_t nDestIndex, size_t nSrcIndex )
344 assign( nDestIndex, get_native( nSrcIndex ));
347 /// Clear value of the slot \p nIndex
348 void clear( size_t nIndex )
350 base_class::clear( nIndex );
353 /// Get current value of slot \p nIndex
354 template <typename T>
355 T * get( size_t nIndex ) const
357 return reinterpret_cast<T *>( get_native( nIndex ) );
360 /// Get native hazard pointer stored
361 guarded_pointer get_native( size_t nIndex ) const
363 return base_class::operator[](nIndex).get();
366 /// Capacity of the guard array
367 static CDS_CONSTEXPR size_t capacity()
375 A guarded pointer is a pair of a pointer and GC's guard.
376 Usually, it is used for returning a pointer to the item from an lock-free container.
377 The guard prevents the pointer to be early disposed (freed) by GC.
378 After destructing \p %guarded_ptr object the pointer can be disposed (freed) automatically at any time.
381 - \p GuardedType - a type which the guard stores
382 - \p ValueType - a value type
383 - \p Cast - a functor for converting <tt>GuardedType*</tt> to <tt>ValueType*</tt>. Default is \p void (no casting).
385 For intrusive containers, \p GuardedType is the same as \p ValueType and no casting is needed.
386 In such case the \p %guarded_ptr is:
388 typedef cds::gc::HP::guarded_ptr< foo > intrusive_guarded_ptr;
391 For standard (non-intrusive) containers \p GuardedType is not the same as \p ValueType and casting is needed.
399 struct value_accessor {
400 std::string* operator()( foo* pFoo ) const
402 return &(pFoo->value);
407 typedef cds::gc::HP::guarded_ptr< Foo, std::string, value_accessor > nonintrusive_guarded_ptr;
410 You don't need use this class directly.
411 All set/map container classes from \p libcds declare the typedef for \p %guarded_ptr with appropriate casting functor.
413 template <typename GuardedType, typename ValueType=GuardedType, typename Cast=void >
417 struct trivial_cast {
418 ValueType * operator()( GuardedType * p ) const
426 typedef GuardedType guarded_type; ///< Guarded type
427 typedef ValueType value_type; ///< Value type
429 /// Functor for casting \p guarded_type to \p value_type
430 typedef typename std::conditional< std::is_same<Cast, void>::value, trivial_cast, Cast >::type value_cast;
433 typedef cds::gc::hp::details::hp_guard native_guard;
438 native_guard * m_pGuard;
442 /// Creates empty guarded pointer
443 guarded_ptr() CDS_NOEXCEPT
448 /// Initializes guarded pointer with \p p
449 explicit guarded_ptr( guarded_type * p ) CDS_NOEXCEPT
455 explicit guarded_ptr( std::nullptr_t ) CDS_NOEXCEPT
456 : m_pGuard( nullptr )
461 guarded_ptr( guarded_ptr&& gp ) CDS_NOEXCEPT
462 : m_pGuard( gp.m_pGuard )
464 gp.m_pGuard = nullptr;
467 /// The guarded pointer is not copy-constructible
468 guarded_ptr( guarded_ptr const& gp ) = delete;
470 /// Clears the guarded pointer
472 \ref release is called if guarded pointer is not \ref empty
474 ~guarded_ptr() CDS_NOEXCEPT
479 /// Move-assignment operator
480 guarded_ptr& operator=( guarded_ptr&& gp ) CDS_NOEXCEPT
482 // Hazard Pointer array is organized as a stack
483 if ( m_pGuard && m_pGuard > gp.m_pGuard ) {
484 m_pGuard->set( gp.m_pGuard->get(atomics::memory_order_relaxed) );
489 m_pGuard = gp.m_pGuard;
490 gp.m_pGuard = nullptr;
495 /// The guarded pointer is not copy-assignable
496 guarded_ptr& operator=(guarded_ptr const& gp) = delete;
498 /// Returns a pointer to guarded value
499 value_type * operator ->() const CDS_NOEXCEPT
502 return value_cast()( reinterpret_cast<guarded_type *>(m_pGuard->get()));
505 /// Returns a reference to guarded value
506 value_type& operator *() CDS_NOEXCEPT
509 return *value_cast()(reinterpret_cast<guarded_type *>(m_pGuard->get()));
512 /// Returns const reference to guarded value
513 value_type const& operator *() const CDS_NOEXCEPT
516 return *value_cast()(reinterpret_cast<guarded_type *>(m_pGuard->get()));
519 /// Checks if the guarded pointer is \p nullptr
520 bool empty() const CDS_NOEXCEPT
522 return !m_pGuard || m_pGuard->get( atomics::memory_order_relaxed ) == nullptr;
525 /// \p bool operator returns <tt>!empty()</tt>
526 explicit operator bool() const CDS_NOEXCEPT
531 /// Clears guarded pointer
533 If the guarded pointer has been released, the pointer can be disposed (freed) at any time.
534 Dereferncing the guarded pointer after \p release() is dangerous.
536 void release() CDS_NOEXCEPT
542 // For internal use only!!!
543 native_guard& guard() CDS_NOEXCEPT
556 m_pGuard = &thread_gc::alloc_guard();
562 thread_gc::free_guard( *m_pGuard );
571 enum class scan_type {
572 classic = hp::classic, ///< classic scan as described in Michael's papers
573 inplace = hp::inplace ///< inplace scan without allocation
575 /// Initializes %HP singleton
577 The constructor initializes GC singleton with passed parameters.
578 If GC instance is not exist then the function creates the instance.
579 Otherwise it does nothing.
581 The Michael's %HP reclamation schema depends of three parameters:
582 - \p nHazardPtrCount - hazard pointer count per thread. Usually it is small number (up to 10) depending from
583 the data structure algorithms. By default, if \p nHazardPtrCount = 0, the function
584 uses maximum of the hazard pointer count for CDS library.
585 - \p nMaxThreadCount - max count of thread with using Hazard Pointer GC in your application. Default is 100.
586 - \p nMaxRetiredPtrCount - capacity of array of retired pointers for each thread. Must be greater than
587 <tt> nHazardPtrCount * nMaxThreadCount </tt>. Default is <tt>2 * nHazardPtrCount * nMaxThreadCount </tt>.
590 size_t nHazardPtrCount = 0, ///< Hazard pointer count per thread
591 size_t nMaxThreadCount = 0, ///< Max count of simultaneous working thread in your application
592 size_t nMaxRetiredPtrCount = 0, ///< Capacity of the array of retired objects for the thread
593 scan_type nScanType = scan_type::inplace ///< Scan type (see \p scan_type enum)
596 hp::GarbageCollector::Construct(
600 static_cast<hp::scan_type>(nScanType)
604 /// Terminates GC singleton
606 The destructor destroys %HP global object. After calling of this function you may \b NOT
607 use CDS data structures based on \p %cds::gc::HP.
608 Usually, %HP object is destroyed at the end of your \p main().
612 hp::GarbageCollector::Destruct( true );
615 /// Checks if count of hazard pointer is no less than \p nCountNeeded
617 If \p bRaiseException is \p true (that is the default), the function raises
618 an \p std::overflow_error exception "Too few hazard pointers"
619 if \p nCountNeeded is more than the count of hazard pointer per thread.
621 static bool check_available_guards( size_t nCountNeeded, bool bRaiseException = true )
623 if ( hp::GarbageCollector::instance().getHazardPointerCount() < nCountNeeded ) {
624 if ( bRaiseException )
625 throw std::overflow_error( "Too few hazard pointers" );
631 /// Returns max Hazard Pointer count
632 static size_t max_hazard_count()
634 return hp::GarbageCollector::instance().getHazardPointerCount();
637 /// Returns max count of thread
638 static size_t max_thread_count()
640 return hp::GarbageCollector::instance().getMaxThreadCount();
643 /// Returns capacity of retired pointer array
644 static size_t retired_array_capacity()
646 return hp::GarbageCollector::instance().getMaxRetiredPtrCount();
649 /// Retire pointer \p p with function \p pFunc
651 The function places pointer \p p to array of pointers ready for removing.
652 (so called retired pointer array). The pointer can be safely removed when no hazard pointer points to it.
653 Deleting the pointer is the function \p pFunc call.
655 template <typename T>
656 static void retire( T * p, void (* pFunc)(T *) ); // inline in hp_impl.h
658 /// Retire pointer \p p with functor of type \p Disposer
660 The function places pointer \p p to array of pointers ready for removing.
661 (so called retired pointer array). The pointer can be safely removed when no hazard pointer points to it.
663 Deleting the pointer is an invocation of some object of type \p Disposer; the interface of \p Disposer is:
665 template <typename T>
667 void operator()( T * p ) ; // disposing operator
670 Since the functor call can happen at any time after \p retire call, additional restrictions are imposed to \p Disposer type:
671 - it should be stateless functor
672 - it should be default-constructible
673 - the result of functor call with argument \p p should not depend on where the functor will be called.
676 Operator \p delete functor:
678 template <typename T>
680 void operator ()( T * p ) {
685 // How to call GC::retire method
688 // ... use p in lock-free manner
690 cds::gc::HP::retire<disposer>( p ) ; // place p to retired pointer array of HP GC
693 Functor based on \p std::allocator :
695 template <typename ALLOC = std::allocator<int> >
697 template <typename T>
698 void operator()( T * p ) {
699 typedef typename ALLOC::templare rebind<T>::other alloc_t;
702 a.deallocate( p, 1 );
707 template <class Disposer, typename T>
708 static void retire( T * p ); // inline in hp_impl.h
710 /// Get current scan strategy
711 static scan_type getScanType()
713 return static_cast<scan_type>( hp::GarbageCollector::instance().getScanType());
716 /// Set current scan strategy
717 static void setScanType(
718 scan_type nScanType ///< new scan strategy
721 hp::GarbageCollector::instance().setScanType( static_cast<hp::scan_type>(nScanType) );
724 /// Checks if Hazard Pointer GC is constructed and may be used
727 return hp::GarbageCollector::isUsed();
730 /// Forced GC cycle call for current thread
732 Usually, this function should not be called directly.
734 static void scan() ; // inline in hp_impl.h
736 /// Synonym for \ref scan()
737 static void force_dispose()
742 }} // namespace cds::gc
744 #endif // #ifndef CDSLIB_GC_IMPL_HP_DECL_H