3 #ifndef __CDS_GC_DETAILS_HP_H
4 #define __CDS_GC_DETAILS_HP_H
6 #include <cds/cxx11_atomic.h>
7 #include <cds/os/thread.h>
8 #include <cds/details/bounded_array.h>
10 #include <cds/gc/details/hp_type.h>
11 #include <cds/gc/details/hp_alloc.h>
13 #if CDS_COMPILER == CDS_COMPILER_MSVC
14 # pragma warning(push)
15 // warning C4251: 'cds::gc::hp::GarbageCollector::m_pListHead' : class 'cds::cxx11_atomic::atomic<T>'
16 // needs to have dll-interface to be used by clients of class 'cds::gc::hp::GarbageCollector'
17 # pragma warning(disable: 4251)
22 2007.12.24 khizmax Add statistics and CDS_GATHER_HAZARDPTR_STAT macro
23 2008.03.06 khizmax Refactoring: implementation of HazardPtrMgr is moved to hazardptr.cpp
24 2008.03.08 khizmax Remove HazardPtrMgr singleton. Now you must initialize/destroy HazardPtrMgr calling
25 HazardPtrMgr::Construct / HazardPtrMgr::Destruct before use (usually in main() function).
26 2008.12.06 khizmax Refactoring. Changes class name, namespace hierarchy, all helper defs have been moved to details namespace
27 2010.01.27 khizmax Introducing memory order constraint
32 @page cds_garbage_collectors_comparison GC comparison
33 @ingroup cds_garbage_collector
39 <th>%cds::gc::DHP</th>
42 <td>Implementation quality</td>
47 <td>Performance rank (1 - slowest, 5 - fastest)</td>
52 <td>Max number of guarded (hazard) pointers per thread</td>
53 <td>limited (specifies in GC object ctor)</td>
54 <td>unlimited (dynamically allocated when needed)</td>
57 <td>Max number of retired pointers<sup>1</sup></td>
62 <td>Array of retired pointers</td>
63 <td>preallocated for each thread, limited in size</td>
64 <td>global for the entire process, unlimited (dynamically allocated when needed)</td>
67 <td>Support direct pointer to item of lock-free container (useful for iterators)</td>
68 <td>not supported</td>
69 <td>not supported</td>
73 <sup>1</sup>Unbounded count of retired pointer means a possibility of memory exhaustion.
76 /// Different safe memory reclamation schemas (garbage collectors)
77 /** @ingroup cds_garbage_collector
79 This namespace specifies different safe memory reclamation (SMR) algorithms.
80 See \ref cds_garbage_collector "Garbage collectors"
84 /// Michael's Hazard Pointers reclamation schema
87 - [2002] Maged M.Michael "Safe memory reclamation for dynamic lock-freeobjects using atomic reads and writes"
88 - [2003] Maged M.Michael "Hazard Pointers: Safe memory reclamation for lock-free objects"
89 - [2004] Andrei Alexandrescy, Maged Michael "Lock-free Data Structures with Hazard Pointers"
91 The \p cds::gc::hp namespace and its members are internal representation of Hazard Pointer GC and should not be used directly.
92 Use \p cds::gc::HP class in your code.
94 Hazard Pointer garbage collector is a singleton. The main user-level part of Hazard Pointer schema is
95 GC class and its nested classes. Before use any HP-related class you must initialize HP garbage collector
96 by contructing \p cds::gc::HP object in beginning of your \p main().
97 See \p cds::gc::HP class for explanation.
102 class GarbageCollector;
108 typedef cds::gc::details::retired_ptr retired_ptr;
110 /// Array of retired pointers
112 The vector of retired pointer ready to delete.
114 The Hazard Pointer schema is build on thread-static arrays. For each HP-enabled thread the HP manager allocates
115 array of retired pointers. The array belongs to the thread: owner thread writes to the array, other threads
118 class retired_vector {
119 /// Underlying vector implementation
120 typedef cds::details::bounded_array<retired_ptr> retired_vector_impl;
122 retired_vector_impl m_arr ; ///< the array of retired pointers
123 size_t m_nSize ; ///< Current size of \p m_arr
127 typedef retired_vector_impl::iterator iterator;
130 retired_vector( const cds::gc::hp::GarbageCollector& HzpMgr ) CDS_NOEXCEPT; // inline
136 The capacity is constant for any thread. It is defined by cds::gc::hp::GarbageCollector.
138 size_t capacity() const CDS_NOEXCEPT
140 return m_arr.capacity();
143 /// Current vector size (count of retired pointers in the vector)
144 size_t size() const CDS_NOEXCEPT
149 /// Set vector size. Uses internally
150 void size( size_t nSize )
152 assert( nSize <= capacity() );
156 /// Pushes retired pointer to the vector
157 void push( const retired_ptr& p )
159 assert( m_nSize < capacity() );
160 m_arr[ m_nSize ] = p;
164 /// Checks if the vector is full (size() == capacity() )
165 bool isFull() const CDS_NOEXCEPT
167 return m_nSize >= capacity();
171 iterator begin() CDS_NOEXCEPT
173 return m_arr.begin();
177 iterator end() CDS_NOEXCEPT
179 return m_arr.begin() + m_nSize ;
182 /// Clears the vector. After clearing, size() == 0
183 void clear() CDS_NOEXCEPT
189 /// Hazard pointer record of the thread
191 The structure of type "single writer - multiple reader": only the owner thread may write to this structure
192 other threads have read-only access.
195 hp_allocator<> m_hzp; ///< array of hazard pointers. Implicit \ref CDS_DEFAULT_ALLOCATOR dependency
196 retired_vector m_arrRetired ; ///< Retired pointer array
199 hp_record( const cds::gc::hp::GarbageCollector& HzpMgr ); // inline
203 /// Clears all hazard pointers
209 } // namespace details
211 /// GarbageCollector::Scan phase strategy
213 See GarbageCollector::Scan for explanation
216 classic, ///< classic scan as described in Michael's works (see GarbageCollector::classic_scan)
217 inplace ///< inplace scan without allocation (see GarbageCollector::inplace_scan)
220 /// Hazard Pointer singleton
222 Safe memory reclamation schema by Michael "Hazard Pointers"
225 \li [2002] Maged M.Michael "Safe memory reclamation for dynamic lock-freeobjects using atomic reads and writes"
226 \li [2003] Maged M.Michael "Hazard Pointers: Safe memory reclamation for lock-free objects"
227 \li [2004] Andrei Alexandrescy, Maged Michael "Lock-free Data Structures with Hazard Pointers"
230 class CDS_EXPORT_API GarbageCollector
233 typedef cds::atomicity::event_counter event_counter ; ///< event counter type
235 /// Internal GC statistics
236 struct InternalState {
237 size_t nHPCount ; ///< HP count per thread (const)
238 size_t nMaxThreadCount ; ///< Max thread count (const)
239 size_t nMaxRetiredPtrCount ; ///< Max retired pointer count per thread (const)
240 size_t nHPRecSize ; ///< Size of HP record, bytes (const)
242 size_t nHPRecAllocated ; ///< Count of HP record allocations
243 size_t nHPRecUsed ; ///< Count of HP record used
244 size_t nTotalRetiredPtrCount ; ///< Current total count of retired pointers
245 size_t nRetiredPtrInFreeHPRecs ; ///< Count of retired pointer in free (unused) HP records
247 event_counter::value_type evcAllocHPRec ; ///< Count of \p hp_record allocations
248 event_counter::value_type evcRetireHPRec ; ///< Count of \p hp_record retire events
249 event_counter::value_type evcAllocNewHPRec; ///< Count of new \p hp_record allocations from heap
250 event_counter::value_type evcDeleteHPRec ; ///< Count of \p hp_record deletions
252 event_counter::value_type evcScanCall ; ///< Count of Scan calling
253 event_counter::value_type evcHelpScanCall ; ///< Count of HelpScan calling
254 event_counter::value_type evcScanFromHelpScan;///< Count of Scan calls from HelpScan
256 event_counter::value_type evcDeletedNode ; ///< Count of deleting of retired objects
257 event_counter::value_type evcDeferredNode ; ///< Count of objects that cannot be deleted in Scan phase because of a hazard_pointer guards it
260 /// No GarbageCollector object is created
261 CDS_DECLARE_EXCEPTION( HZPManagerEmpty, "Global Hazard Pointer GarbageCollector is NULL" );
263 /// Not enough required Hazard Pointer count
264 CDS_DECLARE_EXCEPTION( HZPTooMany, "Not enough required Hazard Pointer count" );
267 /// Internal GC statistics
269 event_counter m_AllocHPRec ; ///< Count of \p hp_record allocations
270 event_counter m_RetireHPRec ; ///< Count of \p hp_record retire events
271 event_counter m_AllocNewHPRec ; ///< Count of new \p hp_record allocations from heap
272 event_counter m_DeleteHPRec ; ///< Count of \p hp_record deletions
274 event_counter m_ScanCallCount ; ///< Count of Scan calling
275 event_counter m_HelpScanCallCount ; ///< Count of HelpScan calling
276 event_counter m_CallScanFromHelpScan ; ///< Count of Scan calls from HelpScan
278 event_counter m_DeletedNode ; ///< Count of retired objects deleting
279 event_counter m_DeferredNode ; ///< Count of objects that cannot be deleted in Scan phase because of a hazard_pointer guards it
282 /// Internal list of cds::gc::hp::details::hp_record
283 struct hplist_node : public details::hp_record
285 hplist_node * m_pNextNode ; ///< next hazard ptr record in list
286 atomics::atomic<OS::ThreadId> m_idOwner ; ///< Owner thread id; 0 - the record is free (not owned)
287 atomics::atomic<bool> m_bFree ; ///< true if record if free (not owned)
290 hplist_node( const GarbageCollector& HzpMgr )
291 : hp_record( HzpMgr ),
292 m_pNextNode( nullptr ),
293 m_idOwner( OS::c_NullThreadId ),
299 assert( m_idOwner.load( atomics::memory_order_relaxed ) == OS::c_NullThreadId );
300 assert( m_bFree.load(atomics::memory_order_relaxed) );
305 atomics::atomic<hplist_node *> m_pListHead ; ///< Head of GC list
307 static GarbageCollector * m_pHZPManager ; ///< GC instance pointer
309 Statistics m_Stat ; ///< Internal statistics
310 bool m_bStatEnabled ; ///< true - statistics enabled
312 const size_t m_nHazardPointerCount ; ///< max count of thread's hazard pointer
313 const size_t m_nMaxThreadCount ; ///< max count of thread
314 const size_t m_nMaxRetiredPtrCount ; ///< max count of retired ptr per thread
315 scan_type m_nScanType ; ///< scan type (see \ref scan_type enum)
321 size_t nHazardPtrCount = 0, ///< Hazard pointer count per thread
322 size_t nMaxThreadCount = 0, ///< Max count of thread
323 size_t nMaxRetiredPtrCount = 0, ///< Capacity of the array of retired objects
324 scan_type nScanType = inplace ///< Scan type (see \ref scan_type enum)
330 /// Allocate new HP record
331 hplist_node * NewHPRec();
333 /// Permanently deletes HPrecord \p pNode
335 Caveat: for performance reason this function is defined as inline and cannot be called directly
337 void DeleteHPRec( hplist_node * pNode );
339 /// Permanently deletes retired pointer \p p
341 Caveat: for performance reason this function is defined as inline and cannot be called directly
343 void DeletePtr( details::retired_ptr& p );
346 void detachAllThread();
350 /// Creates GarbageCollector singleton
352 GC is the singleton. If GC instance is not exist then the function creates the instance.
353 Otherwise it does nothing.
355 The Michael's HP reclamation schema depends of three parameters:
357 \p nHazardPtrCount - HP pointer count per thread. Usually it is small number (2-4) depending from
358 the data structure algorithms. By default, if \p nHazardPtrCount = 0,
359 the function uses maximum of HP count for CDS library.
361 \p nMaxThreadCount - max count of thread with using HP GC in your application. Default is 100.
363 \p nMaxRetiredPtrCount - capacity of array of retired pointers for each thread. Must be greater than
364 \p nHazardPtrCount * \p nMaxThreadCount.
365 Default is 2 * \p nHazardPtrCount * \p nMaxThreadCount.
367 static void CDS_STDCALL Construct(
368 size_t nHazardPtrCount = 0, ///< Hazard pointer count per thread
369 size_t nMaxThreadCount = 0, ///< Max count of simultaneous working thread in your application
370 size_t nMaxRetiredPtrCount = 0, ///< Capacity of the array of retired objects for the thread
371 scan_type nScanType = inplace ///< Scan type (see \ref scan_type enum)
374 /// Destroys global instance of GarbageCollector
376 The parameter \p bDetachAll should be used carefully: if its value is \p true,
377 then the destroying GC automatically detaches all attached threads. This feature
378 can be useful when you have no control over the thread termination, for example,
379 when \p libcds is injected into existing external thread.
381 static void CDS_STDCALL Destruct(
382 bool bDetachAll = false ///< Detach all threads
385 /// Returns pointer to GarbageCollector instance
386 static GarbageCollector& instance()
388 if ( !m_pHZPManager )
389 throw HZPManagerEmpty();
390 return *m_pHZPManager;
393 /// Checks if global GC object is constructed and may be used
394 static bool isUsed() CDS_NOEXCEPT
396 return m_pHZPManager != nullptr;
399 /// Returns max Hazard Pointer count defined in construction time
400 size_t getHazardPointerCount() const CDS_NOEXCEPT
402 return m_nHazardPointerCount;
405 /// Returns max thread count defined in construction time
406 size_t getMaxThreadCount() const CDS_NOEXCEPT
408 return m_nMaxThreadCount;
411 /// Returns max size of retired objects array. It is defined in construction time
412 size_t getMaxRetiredPtrCount() const CDS_NOEXCEPT
414 return m_nMaxRetiredPtrCount;
417 // Internal statistics
419 /// Get internal statistics
420 InternalState& getInternalState(InternalState& stat) const;
422 /// Checks if internal statistics enabled
423 bool isStatisticsEnabled() const { return m_bStatEnabled; }
425 /// Enables/disables internal statistics
426 bool enableStatistics( bool bEnable )
428 bool bEnabled = m_bStatEnabled;
429 m_bStatEnabled = bEnable;
433 /// Checks that required hazard pointer count \p nRequiredCount is less or equal then max hazard pointer count
435 If \p nRequiredCount > getHazardPointerCount() then the exception HZPTooMany is thrown
437 static void checkHPCount( unsigned int nRequiredCount )
439 if ( instance().getHazardPointerCount() < nRequiredCount )
443 /// Get current scan strategy
444 scan_type getScanType() const
449 /// Set current scan strategy
450 /** @anchor hzp_gc_setScanType
451 Scan strategy changing is allowed on the fly.
454 scan_type nScanType ///< new scan strategy
457 m_nScanType = nScanType;
460 public: // Internals for threads
462 /// Allocates Hazard Pointer GC record. For internal use only
463 details::hp_record * alloc_hp_record();
465 /// Free HP record. For internal use only
466 void free_hp_record( details::hp_record * pRec );
468 /// The main garbage collecting function
470 This function is called internally by ThreadGC object when upper bound of thread's list of reclaimed pointers
473 There are the following scan algorithm:
474 - \ref hzp_gc_classic_scan "classic_scan" allocates memory for internal use
475 - \ref hzp_gc_inplace_scan "inplace_scan" does not allocate any memory
477 Use \ref hzp_gc_setScanType "setScanType" member function to setup appropriate scan algorithm.
479 void Scan( details::hp_record * pRec )
481 switch ( m_nScanType ) {
483 inplace_scan( pRec );
486 assert(false) ; // Forgotten something?..
488 classic_scan( pRec );
493 /// Helper scan routine
495 The function guarantees that every node that is eligible for reuse is eventually freed, barring
496 thread failures. To do so, after executing Scan, a thread executes a HelpScan,
497 where it checks every HP record. If an HP record is inactive, the thread moves all "lost" reclaimed pointers
498 to thread's list of reclaimed pointers.
500 The function is called internally by Scan.
502 void HelpScan( details::hp_record * pThis );
505 /// Classic scan algorithm
506 /** @anchor hzp_gc_classic_scan
507 Classical scan algorithm as described in Michael's paper.
509 A scan includes four stages. The first stage involves scanning the array HP for non-null values.
510 Whenever a non-null value is encountered, it is inserted in a local list of currently protected pointer.
511 Only stage 1 accesses shared variables. The following stages operate only on private variables.
513 The second stage of a scan involves sorting local list of protected pointers to allow
514 binary search in the third stage.
516 The third stage of a scan involves checking each reclaimed node
517 against the pointers in local list of protected pointers. If the binary search yields
518 no match, the node is freed. Otherwise, it cannot be deleted now and must kept in thread's list
519 of reclaimed pointers.
521 The forth stage prepares new thread's private list of reclaimed pointers
522 that could not be freed during the current scan, where they remain until the next scan.
524 This algorithm allocates memory for internal HP array.
526 This function is called internally by ThreadGC object when upper bound of thread's list of reclaimed pointers
529 void classic_scan( details::hp_record * pRec );
531 /// In-place scan algorithm
532 /** @anchor hzp_gc_inplace_scan
533 Unlike the \ref hzp_gc_classic_scan "classic_scan" algorithm, \p inplace_scan does not allocate any memory.
534 All operations are performed in-place.
536 void inplace_scan( details::hp_record * pRec );
539 /// Thread's hazard pointer manager
541 To use Hazard Pointer reclamation schema each thread object must be linked with the object of ThreadGC class
542 that interacts with GarbageCollector global object. The linkage is performed by calling \ref cds_threading "cds::threading::Manager::attachThread()"
543 on the start of each thread that uses HP GC. Before terminating the thread linked to HP GC it is necessary to call
544 \ref cds_threading "cds::threading::Manager::detachThread()".
548 GarbageCollector& m_HzpManager; ///< Hazard Pointer GC singleton
549 details::hp_record * m_pHzpRec; ///< Pointer to thread's HZP record
552 /// Default constructor
554 : m_HzpManager( GarbageCollector::instance() ),
558 /// The object is not copy-constructible
559 ThreadGC( ThreadGC const& ) = delete;
566 /// Checks if thread GC is initialized
567 bool isInitialized() const { return m_pHzpRec != nullptr; }
569 /// Initialization. Repeat call is available
573 m_pHzpRec = m_HzpManager.alloc_hp_record();
576 /// Finalization. Repeat call is available
580 details::hp_record * pRec = m_pHzpRec;
582 m_HzpManager.free_hp_record( pRec );
586 /// Initializes HP guard \p guard
587 details::hp_guard& allocGuard()
590 return m_pHzpRec->m_hzp.alloc();
593 /// Frees HP guard \p guard
594 void freeGuard( details::hp_guard& guard )
597 m_pHzpRec->m_hzp.free( guard );
600 /// Initializes HP guard array \p arr
601 template <size_t Count>
602 void allocGuard( details::hp_array<Count>& arr )
605 m_pHzpRec->m_hzp.alloc( arr );
608 /// Frees HP guard array \p arr
609 template <size_t Count>
610 void freeGuard( details::hp_array<Count>& arr )
613 m_pHzpRec->m_hzp.free( arr );
616 /// Places retired pointer \p and its deleter \p pFunc into thread's array of retired pointer for deferred reclamation
617 template <typename T>
618 void retirePtr( T * p, void (* pFunc)(T *) )
629 free_retired_ptr_func hpFunc;
631 cast_func.pFunc = pFunc;
633 retirePtr( details::retired_ptr( cast_ptr.hp, cast_func.hpFunc ) );
635 retirePtr( details::retired_ptr( reinterpret_cast<void *>( p ), reinterpret_cast<free_retired_ptr_func>( pFunc ) ) );
638 /// Places retired pointer \p into thread's array of retired pointer for deferred reclamation
639 void retirePtr( details::retired_ptr const& p )
641 m_pHzpRec->m_arrRetired.push( p );
643 if ( m_pHzpRec->m_arrRetired.isFull() ) {
644 // Max of retired pointer count is reached. Do scan
652 m_HzpManager.Scan( m_pHzpRec );
653 m_HzpManager.HelpScan( m_pHzpRec );
660 This class encapsulates Hazard Pointer guard to protect a pointer against deletion .
661 It allocates one HP from thread's HP array in constructor and free the hazard pointer allocated
667 details::hp_guard& m_hp ; ///< Hazard pointer guarded
668 ThreadGC& m_gc ; ///< Thread GC
672 typedef details::hp_guard::hazard_ptr hazard_ptr ; ///< Hazard pointer type
674 /// Allocates HP guard from \p gc
675 guard( ThreadGC& gc )
676 : m_hp( gc.allocGuard() )
680 /// Allocates HP guard from \p gc and protects the pointer \p p of type \p T
681 template <typename T>
682 guard( ThreadGC& gc, T * p )
683 : m_hp( gc.allocGuard() )
689 /// Frees HP guard. The pointer guarded may be deleted after this.
692 m_gc.freeGuard( m_hp );
695 /// Returns thread GC
696 ThreadGC& getGC() const
701 /// Protects the pointer \p p against reclamation (guards the pointer).
702 template <typename T>
703 T * operator =( T * p )
709 std::nullptr_t operator =(std::nullptr_t)
711 return m_hp = nullptr;
714 hazard_ptr get() const
721 /// Auto-managed array of hazard pointers
723 This class is wrapper around cds::gc::hp::details::hp_array class.
724 \p Count is the size of HP array
726 template <size_t Count>
727 class array : public details::hp_array<Count>
729 ThreadGC& m_mgr ; ///< Thread GC
732 /// Rebind array for other size \p COUNT2
733 template <size_t Count2>
735 typedef array<Count2> other; ///< rebinding result
739 /// Allocates array of HP guard from \p mgr
740 array( ThreadGC& mgr )
743 mgr.allocGuard( *this );
746 /// Frees array of HP guard
749 m_mgr.freeGuard( *this );
752 /// Returns thread GC
753 ThreadGC& getGC() const { return m_mgr; }
757 }} // namespace cds::gc
760 #include <cds/gc/details/hp_inline.h>
762 #if CDS_COMPILER == CDS_COMPILER_MSVC
763 # pragma warning(pop)
766 #endif // #ifndef __CDS_GC_DETAILS_HP_H