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_GC_HP_SMR_H
32 #define CDSLIB_GC_HP_SMR_H
35 #include <cds/gc/details/hp_common.h>
36 #include <cds/details/lib.h>
37 #include <cds/threading/model.h>
38 #include <cds/details/throw_exception.h>
39 #include <cds/details/static_functor.h>
40 #include <cds/details/marked_ptr.h>
41 #include <cds/user_setup/cache_line.h>
44 @page cds_garbage_collectors_comparison Hazard Pointer SMR implementations
45 @ingroup cds_garbage_collector
51 <th>%cds::gc::DHP</th>
54 <td>Max number of guarded (hazard) pointers per thread</td>
55 <td>limited (specified at construction time)</td>
56 <td>unlimited (dynamically allocated when needed)</td>
59 <td>Max number of retired pointers<sup>1</sup></td>
60 <td>bounded, specified at construction time</td>
61 <td>bounded, adaptive, depends on current thread count and number of hazard pointer for each thread</td>
65 <td>bounded, upper bound is specified at construction time</td>
70 <sup>1</sup>Unbounded count of retired pointers means a possibility of memory exhaustion.
74 /// @defgroup cds_garbage_collector Garbage collectors
77 /// Different safe memory reclamation schemas (garbage collectors)
78 /** @ingroup cds_garbage_collector
80 This namespace specifies different safe memory reclamation (SMR) algorithms.
81 See \ref cds_garbage_collector "Garbage collectors"
89 namespace cds { namespace gc {
90 /// Hazard pointer implementation details
92 using namespace cds::gc::hp::common;
94 /// Exception "Not enough Hazard Pointer"
95 class not_enought_hazard_ptr: public std::length_error
99 not_enought_hazard_ptr()
100 : std::length_error( "Not enough Hazard Pointer" )
105 /// Exception "Hazard Pointer SMR is not initialized"
106 class not_initialized: public std::runtime_error
111 : std::runtime_error( "Global Hazard Pointer SMR object is not initialized" )
117 /// Per-thread hazard pointer storage
118 class thread_hp_storage {
120 thread_hp_storage( guard* arr, size_t nSize ) CDS_NOEXCEPT
124 # ifdef CDS_ENABLE_HPSTAT
125 , alloc_guard_count_(0)
126 , free_guard_count_(0)
130 new( arr ) guard[nSize];
132 for ( guard* pEnd = arr + nSize - 1; arr < pEnd; ++arr )
133 arr->next_ = arr + 1;
134 arr->next_ = nullptr;
137 thread_hp_storage() = delete;
138 thread_hp_storage( thread_hp_storage const& ) = delete;
139 thread_hp_storage( thread_hp_storage&& ) = delete;
141 size_t capacity() const CDS_NOEXCEPT
146 bool full() const CDS_NOEXCEPT
148 return free_head_ == nullptr;
153 # ifdef CDS_DISABLE_SMR_EXCEPTION
157 CDS_THROW_EXCEPTION( not_enought_hazard_ptr());
159 guard* g = free_head_;
160 free_head_ = g->next_;
161 CDS_HPSTAT( ++alloc_guard_count_ );
165 void free( guard* g ) CDS_NOEXCEPT
167 assert( g >= array_ && g < array_ + capacity() );
171 g->next_ = free_head_;
173 CDS_HPSTAT( ++free_guard_count_ );
177 template< size_t Capacity>
178 size_t alloc( guard_array<Capacity>& arr )
181 guard* g = free_head_;
182 for ( i = 0; i < Capacity && g; ++i ) {
187 # ifdef CDS_DISABLE_SMR_EXCEPTION
188 assert( i == Capacity );
191 CDS_THROW_EXCEPTION( not_enought_hazard_ptr());
194 CDS_HPSTAT( alloc_guard_count_ += Capacity );
198 template <size_t Capacity>
199 void free( guard_array<Capacity>& arr ) CDS_NOEXCEPT
201 guard* gList = free_head_;
202 for ( size_t i = 0; i < Capacity; ++i ) {
208 CDS_HPSTAT( ++free_guard_count_ );
214 // cppcheck-suppress functionConst
217 for ( guard* cur = array_, *last = array_ + capacity(); cur < last; ++cur )
221 guard& operator[]( size_t idx )
223 assert( idx < capacity() );
228 static size_t calc_array_size( size_t capacity )
230 return sizeof( guard ) * capacity;
234 guard* free_head_; ///< Head of free guard list
235 guard* const array_; ///< HP array
236 size_t const capacity_; ///< HP array capacity
237 # ifdef CDS_ENABLE_HPSTAT
239 size_t alloc_guard_count_;
240 size_t free_guard_count_;
246 /// Per-thread retired array
250 retired_array( retired_ptr* arr, size_t capacity ) CDS_NOEXCEPT
252 , last_( arr + capacity )
254 # ifdef CDS_ENABLE_HPSTAT
255 , retire_call_count_(0)
259 retired_array() = delete;
260 retired_array( retired_array const& ) = delete;
261 retired_array( retired_array&& ) = delete;
263 size_t capacity() const CDS_NOEXCEPT
265 return last_ - retired_;
268 size_t size() const CDS_NOEXCEPT
270 return current_ - retired_;
273 bool push( retired_ptr&& p ) CDS_NOEXCEPT
276 CDS_HPSTAT( ++retire_call_count_ );
277 return ++current_ < last_;
280 retired_ptr* first() const CDS_NOEXCEPT
285 retired_ptr* last() const CDS_NOEXCEPT
290 void reset( size_t nSize ) CDS_NOEXCEPT
292 current_ = first() + nSize;
295 bool full() const CDS_NOEXCEPT
297 return current_ == last_;
300 static size_t calc_array_size( size_t capacity )
302 return sizeof( retired_ptr ) * capacity;
306 retired_ptr* current_;
307 retired_ptr* const last_;
308 retired_ptr* const retired_;
309 # ifdef CDS_ENABLE_HPSTAT
311 size_t retire_call_count_;
316 /// Internal statistics
318 size_t guard_allocated; ///< Count of allocated HP guards
319 size_t guard_freed; ///< Count of freed HP guards
320 size_t retired_count; ///< Count of retired pointers
321 size_t free_count; ///< Count of free pointers
322 size_t scan_count; ///< Count of \p scan() call
323 size_t help_scan_count; ///< Count of \p help_scan() call
325 size_t thread_rec_count; ///< Count of thread records
333 /// Clears all counters
342 thread_rec_count = 0;
349 thread_hp_storage hazards_; ///< Hazard pointers private to the thread
350 retired_array retired_; ///< Retired data private to the thread
352 stat stat_; ///< Internal statistics for the thread
354 char pad1_[cds::c_nCacheLineSize];
355 atomics::atomic<unsigned int> sync_; ///< dummy var to introduce synchronizes-with relationship between threads
356 char pad2_[cds::c_nCacheLineSize];
358 // CppCheck warn: pad1_ and pad2_ is uninitialized in ctor
359 // cppcheck-suppress uninitMemberVar
360 thread_data( guard* guards, size_t guard_count, retired_ptr* retired_arr, size_t retired_capacity )
361 : hazards_( guards, guard_count )
362 , retired_( retired_arr, retired_capacity )
366 thread_data() = delete;
367 thread_data( thread_data const& ) = delete;
368 thread_data( thread_data&& ) = delete;
372 sync_.fetch_add( 1, atomics::memory_order_acq_rel );
377 /// \p smr::scan() strategy
379 classic, ///< classic scan as described in Michael's works (see smr::classic_scan() )
380 inplace ///< inplace scan without allocation (see smr::inplace_scan() )
384 /// Hazard Pointer SMR (Safe Memory Reclamation)
387 struct thread_record;
390 /// Returns the instance of Hazard Pointer \ref smr
391 static smr& instance()
393 # ifdef CDS_DISABLE_SMR_EXCEPTION
394 assert( instance_ != nullptr );
397 CDS_THROW_EXCEPTION( not_initialized());
402 /// Creates Hazard Pointer SMR singleton
404 Hazard Pointer SMR is a singleton. If HP instance is not initialized then the function creates the instance.
405 Otherwise it does nothing.
407 The Michael's HP reclamation schema depends of three parameters:
408 - \p nHazardPtrCount - HP pointer count per thread. Usually it is small number (2-4) depending from
409 the data structure algorithms. By default, if \p nHazardPtrCount = 0,
410 the function uses maximum of HP count for CDS library
411 - \p nMaxThreadCount - max count of thread with using HP GC in your application. Default is 100.
412 - \p nMaxRetiredPtrCount - capacity of array of retired pointers for each thread. Must be greater than
413 <tt> nHazardPtrCount * nMaxThreadCount </tt>
414 Default is <tt>2 * nHazardPtrCount * nMaxThreadCount</tt>
416 static CDS_EXPORT_API void construct(
417 size_t nHazardPtrCount = 0, ///< Hazard pointer count per thread
418 size_t nMaxThreadCount = 0, ///< Max count of simultaneous working thread in your application
419 size_t nMaxRetiredPtrCount = 0, ///< Capacity of the array of retired objects for the thread
420 scan_type nScanType = inplace ///< Scan type (see \ref scan_type enum)
423 // for back-copatibility
424 static void Construct(
425 size_t nHazardPtrCount = 0, ///< Hazard pointer count per thread
426 size_t nMaxThreadCount = 0, ///< Max count of simultaneous working thread in your application
427 size_t nMaxRetiredPtrCount = 0, ///< Capacity of the array of retired objects for the thread
428 scan_type nScanType = inplace ///< Scan type (see \ref scan_type enum)
431 construct( nHazardPtrCount, nMaxThreadCount, nMaxRetiredPtrCount, nScanType );
434 /// Destroys global instance of \ref smr
436 The parameter \p bDetachAll should be used carefully: if its value is \p true,
437 then the object destroyed automatically detaches all attached threads. This feature
438 can be useful when you have no control over the thread termination, for example,
439 when \p libcds is injected into existing external thread.
441 static CDS_EXPORT_API void destruct(
442 bool bDetachAll = false ///< Detach all threads
445 // for back-compatibility
446 static void Destruct(
447 bool bDetachAll = false ///< Detach all threads
450 destruct( bDetachAll );
453 /// Checks if global SMR object is constructed and may be used
454 static bool isUsed() CDS_NOEXCEPT
456 return instance_ != nullptr;
459 /// Set memory management functions
461 @note This function may be called <b>BEFORE</b> creating an instance
462 of Hazard Pointer SMR
464 SMR object allocates some memory for thread-specific data and for
466 By default, a standard \p new and \p delete operators are used for this.
468 static CDS_EXPORT_API void set_memory_allocator(
469 void* ( *alloc_func )( size_t size ),
470 void (*free_func )( void * p )
473 /// Returns max Hazard Pointer count per thread
474 size_t get_hazard_ptr_count() const CDS_NOEXCEPT
476 return hazard_ptr_count_;
479 /// Returns max thread count
480 size_t get_max_thread_count() const CDS_NOEXCEPT
482 return max_thread_count_;
485 /// Returns max size of retired objects array
486 size_t get_max_retired_ptr_count() const CDS_NOEXCEPT
488 return max_retired_ptr_count_;
491 /// Get current scan strategy
492 scan_type get_scan_type() const
497 /// Checks that required hazard pointer count \p nRequiredCount is less or equal then max hazard pointer count
499 If <tt> nRequiredCount > get_hazard_ptr_count()</tt> then the exception \p not_enought_hazard_ptr is thrown
501 static void check_hazard_ptr_count( size_t nRequiredCount )
503 if ( instance().get_hazard_ptr_count() < nRequiredCount ) {
504 # ifdef CDS_DISABLE_SMR_EXCEPTION
505 assert( false ); // not enough hazard ptr
507 CDS_THROW_EXCEPTION( not_enought_hazard_ptr() );
512 /// Returns thread-local data for the current thread
513 static CDS_EXPORT_API thread_data* tls();
515 static CDS_EXPORT_API void attach_thread();
516 static CDS_EXPORT_API void detach_thread();
518 /// Get internal statistics
519 void statistics( stat& st );
521 public: // for internal use only
522 /// The main garbage collecting function
524 This function is called internally when upper bound of thread's list of reclaimed pointers
527 There are the following scan algorithm:
528 - \ref hzp_gc_classic_scan "classic_scan" allocates memory for internal use
529 - \ref hzp_gc_inplace_scan "inplace_scan" does not allocate any memory
531 Use \p set_scan_type() member function to setup appropriate scan algorithm.
533 void scan( thread_data* pRec )
535 ( this->*scan_func_ )( pRec );
538 /// Helper scan routine
540 The function guarantees that every node that is eligible for reuse is eventually freed, barring
541 thread failures. To do so, after executing \p scan(), a thread executes a \p %help_scan(),
542 where it checks every HP record. If an HP record is inactive, the thread moves all "lost" reclaimed pointers
543 to thread's list of reclaimed pointers.
545 The function is called internally by \p scan().
547 CDS_EXPORT_API void help_scan( thread_data* pThis );
551 size_t nHazardPtrCount, ///< Hazard pointer count per thread
552 size_t nMaxThreadCount, ///< Max count of simultaneous working thread in your application
553 size_t nMaxRetiredPtrCount, ///< Capacity of the array of retired objects for the thread
554 scan_type nScanType ///< Scan type (see \ref scan_type enum)
557 CDS_EXPORT_API ~smr();
559 CDS_EXPORT_API void detach_all_thread();
561 /// Classic scan algorithm
562 /** @anchor hzp_gc_classic_scan
563 Classical scan algorithm as described in Michael's paper.
565 A scan includes four stages. The first stage involves scanning the array HP for non-null values.
566 Whenever a non-null value is encountered, it is inserted in a local list of currently protected pointer.
567 Only stage 1 accesses shared variables. The following stages operate only on private variables.
569 The second stage of a scan involves sorting local list of protected pointers to allow
570 binary search in the third stage.
572 The third stage of a scan involves checking each reclaimed node
573 against the pointers in local list of protected pointers. If the binary search yields
574 no match, the node is freed. Otherwise, it cannot be deleted now and must kept in thread's list
575 of reclaimed pointers.
577 The forth stage prepares new thread's private list of reclaimed pointers
578 that could not be freed during the current scan, where they remain until the next scan.
580 This algorithm allocates memory for internal HP array.
582 This function is called internally by ThreadGC object when upper bound of thread's list of reclaimed pointers
585 CDS_EXPORT_API void classic_scan( thread_data* pRec );
587 /// In-place scan algorithm
588 /** @anchor hzp_gc_inplace_scan
589 Unlike the \p classic_scan() algorithm, \p %inplace_scan() does not allocate any memory.
590 All operations are performed in-place.
592 CDS_EXPORT_API void inplace_scan( thread_data* pRec );
595 CDS_EXPORT_API thread_record* create_thread_data();
596 static CDS_EXPORT_API void destroy_thread_data( thread_record* pRec );
598 /// Allocates Hazard Pointer SMR thread private data
599 CDS_EXPORT_API thread_record* alloc_thread_data();
601 /// Free HP SMR thread-private data
602 CDS_EXPORT_API void free_thread_data( thread_record* pRec );
605 static CDS_EXPORT_API smr* instance_;
607 atomics::atomic< thread_record*> thread_list_; ///< Head of thread list
609 size_t const hazard_ptr_count_; ///< max count of thread's hazard pointer
610 size_t const max_thread_count_; ///< max count of thread
611 size_t const max_retired_ptr_count_; ///< max count of retired ptr per thread
612 scan_type const scan_type_; ///< scan type (see \ref scan_type enum)
613 void ( smr::*scan_func_ )( thread_data* pRec );
618 // for backward compatibility
619 typedef smr GarbageCollector;
624 /// Hazard Pointer SMR (Safe Memory Reclamation)
625 /** @ingroup cds_garbage_collector
627 Implementation of classic Hazard Pointer SMR
630 - [2002] Maged M.Michael "Safe memory reclamation for dynamic lock-freeobjects using atomic reads and writes"
631 - [2003] Maged M.Michael "Hazard Pointers: Safe memory reclamation for lock-free objects"
632 - [2004] Andrei Alexandrescy, Maged Michael "Lock-free Data Structures with Hazard Pointers"
634 Hazard Pointer SMR is a singleton. The main user-level part of Hazard Pointer schema is
635 \p %cds::gc::HP class and its nested classes. Before use any HP-related class you must initialize \p %HP
636 by contructing \p %cds::gc::HP object in beginning of your \p main().
637 See \ref cds_how_to_use "How to use" section for details how to apply SMR schema.
642 /// Native guarded pointer type
643 typedef hp::hazard_ptr guarded_pointer;
646 template <typename T> using atomic_ref = atomics::atomic<T *>;
648 /// Atomic marked pointer
649 template <typename MarkedPtr> using atomic_marked_ptr = atomics::atomic<MarkedPtr>;
652 template <typename T> using atomic_type = atomics::atomic<T>;
654 /// Exception "Not enough Hazard Pointer"
655 typedef hp::not_enought_hazard_ptr not_enought_hazard_ptr_exception;
657 /// Internal statistics
658 typedef hp::stat stat;
660 /// Hazard Pointer guard
662 A guard is a hazard pointer.
663 Additionally, the \p %Guard class manages allocation and deallocation of the hazard pointer.
665 \p %Guard object is movable but not copyable.
667 The guard object can be in two states:
668 - unlinked - the guard is not linked with any internal hazard pointer.
669 In this state no operation except \p link() and move assignment is supported.
670 - linked (default) - the guard allocates an internal hazard pointer and completely operable.
672 Due to performance reason the implementation does not check state of the guard in runtime.
674 @warning Move assignment transfers the guard in unlinked state, use with care.
679 /// Default ctor allocates a guard (hazard pointer) from thread-private storage
681 @warning Can throw \p too_many_hazard_ptr_exception if internal hazard pointer objects are exhausted.
684 : guard_( hp::smr::tls()->hazards_.alloc() )
687 /// Initilalizes an unlinked guard i.e. the guard contains no hazard pointer. Used for move semantics support
688 explicit Guard( std::nullptr_t ) CDS_NOEXCEPT
692 /// Move ctor - \p src guard becomes unlinked (transfer internal guard ownership)
693 Guard( Guard&& src ) CDS_NOEXCEPT
694 : guard_( src.guard_ )
696 src.guard_ = nullptr;
699 /// Move assignment: the internal guards are swapped between \p src and \p this
701 @warning \p src will become in unlinked state if \p this was unlinked on entry.
703 Guard& operator=( Guard&& src ) CDS_NOEXCEPT
705 std::swap( guard_, src.guard_ );
709 /// Copy ctor is prohibited - the guard is not copyable
710 Guard( Guard const& ) = delete;
712 /// Copy assignment is prohibited
713 Guard& operator=( Guard const& ) = delete;
715 /// Frees the internal hazard pointer if the guard is in linked state
721 /// Checks if the guard object linked with any internal hazard pointer
722 bool is_linked() const
724 return guard_ != nullptr;
727 /// Links the guard with internal hazard pointer if the guard is in unlinked state
729 @warning Can throw \p not_enought_hazard_ptr_exception if internal hazard pointer array is exhausted.
734 guard_ = hp::smr::tls()->hazards_.alloc();
737 /// Unlinks the guard from internal hazard pointer; the guard becomes in unlinked state
741 hp::smr::tls()->hazards_.free( guard_ );
746 /// Protects a pointer of type \p atomic<T*>
748 Return the value of \p toGuard
750 The function tries to load \p toGuard and to store it
751 to the HP slot repeatedly until the guard's value equals \p toGuard
753 @warning The guad object should be in linked state, otherwise the result is undefined
755 template <typename T>
756 T protect( atomics::atomic<T> const& toGuard )
758 assert( guard_ != nullptr );
760 T pCur = toGuard.load(atomics::memory_order_acquire);
763 pRet = assign( pCur );
764 pCur = toGuard.load(atomics::memory_order_acquire);
765 } while ( pRet != pCur );
769 /// Protects a converted pointer of type \p atomic<T*>
771 Return the value of \p toGuard
773 The function tries to load \p toGuard and to store result of \p f functor
774 to the HP slot repeatedly until the guard's value equals \p toGuard.
776 The function is useful for intrusive containers when \p toGuard is a node pointer
777 that should be converted to a pointer to the value before protecting.
778 The parameter \p f of type Func is a functor that makes this conversion:
781 value_type * operator()( T * p );
784 Actually, the result of <tt> f( toGuard.load()) </tt> is assigned to the hazard pointer.
786 @warning The guad object should be in linked state, otherwise the result is undefined
788 template <typename T, class Func>
789 T protect( atomics::atomic<T> const& toGuard, Func f )
791 assert( guard_ != nullptr );
793 T pCur = toGuard.load(atomics::memory_order_acquire);
798 pCur = toGuard.load(atomics::memory_order_acquire);
799 } while ( pRet != pCur );
803 /// Store \p p to the guard
805 The function equals to a simple assignment the value \p p to guard, no loop is performed.
806 Can be used for a pointer that cannot be changed concurrently or if the pointer is already
807 guarded by another guard.
809 @warning The guad object should be in linked state, otherwise the result is undefined
811 template <typename T>
814 assert( guard_ != nullptr );
817 hp::smr::tls()->sync();
822 std::nullptr_t assign( std::nullptr_t )
824 assert( guard_ != nullptr );
831 /// Copy a value guarded from \p src guard to \p this guard (valid only in linked state)
832 void copy( Guard const& src )
834 assign( src.get_native());
837 /// Store marked pointer \p p to the guard
839 The function equals to a simple assignment of <tt>p.ptr()</tt>, no loop is performed.
840 Can be used for a marked pointer that cannot be changed concurrently or if the marked pointer
841 is already guarded by another guard.
843 @warning The guard object should be in linked state, otherwise the result is undefined
845 template <typename T, int BITMASK>
846 T * assign( cds::details::marked_ptr<T, BITMASK> p )
848 return assign( p.ptr());
851 /// Clear value of the guard (valid only in linked state)
857 /// Get the value currently protected (valid only in linked state)
858 template <typename T>
861 assert( guard_ != nullptr );
862 return guard_->get_as<T>();
865 /// Get native hazard pointer stored (valid only in linked state)
866 guarded_pointer get_native() const
868 assert( guard_ != nullptr );
869 return guard_->get();
875 hp::guard* g = guard_;
880 hp::guard*& guard_ref()
892 /// Array of Hazard Pointer guards
894 The class is intended for allocating an array of hazard pointer guards.
895 Template parameter \p Count defines the size of the array.
897 template <size_t Count>
901 /// Rebind array for other size \p Count2
902 template <size_t Count2>
904 typedef GuardArray<Count2> other; ///< rebinding result
908 static CDS_CONSTEXPR const size_t c_nCapacity = Count;
911 /// Default ctor allocates \p Count hazard pointers
914 hp::smr::tls()->hazards_.alloc( guards_ );
917 /// Move ctor is prohibited
918 GuardArray( GuardArray&& ) = delete;
920 /// Move assignment is prohibited
921 GuardArray& operator=( GuardArray&& ) = delete;
923 /// Copy ctor is prohibited
924 GuardArray( GuardArray const& ) = delete;
926 /// Copy assignment is prohibited
927 GuardArray& operator=( GuardArray const& ) = delete;
929 /// Frees allocated hazard pointers
932 hp::smr::tls()->hazards_.free( guards_ );
935 /// Protects a pointer of type \p atomic<T*>
937 Return the value of \p toGuard
939 The function tries to load \p toGuard and to store it
940 to the slot \p nIndex repeatedly until the guard's value equals \p toGuard
942 template <typename T>
943 T protect( size_t nIndex, atomics::atomic<T> const& toGuard )
945 assert( nIndex < capacity());
949 pRet = assign( nIndex, toGuard.load(atomics::memory_order_acquire));
950 } while ( pRet != toGuard.load(atomics::memory_order_acquire));
955 /// Protects a pointer of type \p atomic<T*>
957 Return the value of \p toGuard
959 The function tries to load \p toGuard and to store it
960 to the slot \p nIndex repeatedly until the guard's value equals \p toGuard
962 The function is useful for intrusive containers when \p toGuard is a node pointer
963 that should be converted to a pointer to the value type before guarding.
964 The parameter \p f of type Func is a functor that makes this conversion:
967 value_type * operator()( T * p );
970 Really, the result of <tt> f( toGuard.load()) </tt> is assigned to the hazard pointer.
972 template <typename T, class Func>
973 T protect( size_t nIndex, atomics::atomic<T> const& toGuard, Func f )
975 assert( nIndex < capacity());
979 assign( nIndex, f( pRet = toGuard.load(atomics::memory_order_acquire)));
980 } while ( pRet != toGuard.load(atomics::memory_order_acquire));
985 /// Store \p to the slot \p nIndex
987 The function equals to a simple assignment, no loop is performed.
989 template <typename T>
990 T * assign( size_t nIndex, T * p )
992 assert( nIndex < capacity() );
994 guards_.set( nIndex, p );
995 hp::smr::tls()->sync();
999 /// Store marked pointer \p p to the guard
1001 The function equals to a simple assignment of <tt>p.ptr()</tt>, no loop is performed.
1002 Can be used for a marked pointer that cannot be changed concurrently.
1004 template <typename T, int BITMASK>
1005 T * assign( size_t nIndex, cds::details::marked_ptr<T, BITMASK> p )
1007 return assign( nIndex, p.ptr());
1010 /// Copy guarded value from \p src guard to slot at index \p nIndex
1011 void copy( size_t nIndex, Guard const& src )
1013 assign( nIndex, src.get_native());
1016 /// Copy guarded value from slot \p nSrcIndex to the slot \p nDestIndex
1017 void copy( size_t nDestIndex, size_t nSrcIndex )
1019 assign( nDestIndex, get_native( nSrcIndex ));
1022 /// Clear value of the slot \p nIndex
1023 void clear( size_t nIndex )
1025 guards_.clear( nIndex );
1028 /// Get current value of slot \p nIndex
1029 template <typename T>
1030 T * get( size_t nIndex ) const
1032 assert( nIndex < capacity() );
1033 return guards_[nIndex]->template get_as<T>();
1036 /// Get native hazard pointer stored
1037 guarded_pointer get_native( size_t nIndex ) const
1039 assert( nIndex < capacity());
1040 return guards_[nIndex]->get();
1044 hp::guard* release( size_t nIndex ) CDS_NOEXCEPT
1046 return guards_.release( nIndex );
1050 /// Capacity of the guard array
1051 static CDS_CONSTEXPR size_t capacity()
1058 hp::guard_array<c_nCapacity> guards_;
1064 A guarded pointer is a pair of a pointer and GC's guard.
1065 Usually, it is used for returning a pointer to an element of a lock-free container.
1066 The guard prevents the pointer to be early disposed (freed) by SMR.
1067 After destructing \p %guarded_ptr object the pointer can be disposed (freed) automatically at any time.
1070 - \p GuardedType - a type which the guard stores
1071 - \p ValueType - a value type
1072 - \p Cast - a functor for converting <tt>GuardedType*</tt> to <tt>ValueType*</tt>. Default is \p void (no casting).
1074 For intrusive containers, \p GuardedType is the same as \p ValueType and no casting is needed.
1075 In such case the \p %guarded_ptr is:
1077 typedef cds::gc::HP::guarded_ptr< foo > intrusive_guarded_ptr;
1080 For standard (non-intrusive) containers \p GuardedType is not the same as \p ValueType and casting is needed.
1088 struct value_accessor {
1089 std::string* operator()( foo* pFoo ) const
1091 return &(pFoo->value);
1096 typedef cds::gc::HP::guarded_ptr< Foo, std::string, value_accessor > nonintrusive_guarded_ptr;
1099 You don't need use this class directly.
1100 All set/map container classes from \p libcds declare the typedef for \p %guarded_ptr with appropriate casting functor.
1102 template <typename GuardedType, typename ValueType=GuardedType, typename Cast=void >
1106 struct trivial_cast {
1107 ValueType * operator()( GuardedType * p ) const
1113 template <typename GT, typename VT, typename C> friend class guarded_ptr;
1117 typedef GuardedType guarded_type; ///< Guarded type
1118 typedef ValueType value_type; ///< Value type
1120 /// Functor for casting \p guarded_type to \p value_type
1121 typedef typename std::conditional< std::is_same<Cast, void>::value, trivial_cast, Cast >::type value_cast;
1124 /// Creates empty guarded pointer
1125 guarded_ptr() CDS_NOEXCEPT
1130 explicit guarded_ptr( hp::guard* g ) CDS_NOEXCEPT
1134 /// Initializes guarded pointer with \p p
1135 explicit guarded_ptr( guarded_type* p ) CDS_NOEXCEPT
1140 explicit guarded_ptr( std::nullptr_t ) CDS_NOEXCEPT
1146 guarded_ptr( guarded_ptr&& gp ) CDS_NOEXCEPT
1147 : guard_( gp.guard_ )
1149 gp.guard_ = nullptr;
1153 template <typename GT, typename VT, typename C>
1154 guarded_ptr( guarded_ptr<GT, VT, C>&& gp ) CDS_NOEXCEPT
1155 : guard_( gp.guard_ )
1157 gp.guard_ = nullptr;
1160 /// Ctor from \p Guard
1161 explicit guarded_ptr( Guard&& g ) CDS_NOEXCEPT
1162 : guard_( g.release())
1165 /// The guarded pointer is not copy-constructible
1166 guarded_ptr( guarded_ptr const& gp ) = delete;
1168 /// Clears the guarded pointer
1170 \ref release() is called if guarded pointer is not \ref empty()
1172 ~guarded_ptr() CDS_NOEXCEPT
1177 /// Move-assignment operator
1178 guarded_ptr& operator=( guarded_ptr&& gp ) CDS_NOEXCEPT
1180 std::swap( guard_, gp.guard_ );
1184 /// Move-assignment from \p Guard
1185 guarded_ptr& operator=( Guard&& g ) CDS_NOEXCEPT
1187 std::swap( guard_, g.guard_ref());
1191 /// The guarded pointer is not copy-assignable
1192 guarded_ptr& operator=(guarded_ptr const& gp) = delete;
1194 /// Returns a pointer to guarded value
1195 value_type * operator ->() const CDS_NOEXCEPT
1198 return value_cast()( guard_->get_as<guarded_type>());
1201 /// Returns a reference to guarded value
1202 value_type& operator *() CDS_NOEXCEPT
1205 return *value_cast()( guard_->get_as<guarded_type>());
1208 /// Returns const reference to guarded value
1209 value_type const& operator *() const CDS_NOEXCEPT
1212 return *value_cast()( guard_->get_as<guarded_type>());
1215 /// Checks if the guarded pointer is \p nullptr
1216 bool empty() const CDS_NOEXCEPT
1218 return !guard_ || guard_->get( atomics::memory_order_relaxed ) == nullptr;
1221 /// \p bool operator returns <tt>!empty()</tt>
1222 explicit operator bool() const CDS_NOEXCEPT
1227 /// Clears guarded pointer
1229 If the guarded pointer has been released, the pointer can be disposed (freed) at any time.
1230 Dereferncing the guarded pointer after \p release() is dangerous.
1232 void release() CDS_NOEXCEPT
1238 // For internal use only!!!
1239 void reset(guarded_type * p) CDS_NOEXCEPT
1252 guard_ = hp::smr::tls()->hazards_.alloc();
1258 hp::smr::tls()->hazards_.free( guard_ );
1272 enum class scan_type {
1273 classic = hp::classic, ///< classic scan as described in Michael's papers
1274 inplace = hp::inplace ///< inplace scan without allocation
1277 /// Initializes %HP singleton
1279 The constructor initializes Hazard Pointer SMR singleton with passed parameters.
1280 If the instance does not yet exist then the function creates the instance.
1281 Otherwise it does nothing.
1283 The Michael's %HP reclamation schema depends of three parameters:
1284 - \p nHazardPtrCount - hazard pointer count per thread. Usually it is small number (up to 10) depending from
1285 the data structure algorithms. If \p nHazardPtrCount = 0, the defaul value 8 is used
1286 - \p nMaxThreadCount - max count of thread with using Hazard Pointer GC in your application. Default is 100.
1287 - \p nMaxRetiredPtrCount - capacity of array of retired pointers for each thread. Must be greater than
1288 <tt> nHazardPtrCount * nMaxThreadCount </tt>. Default is <tt>2 * nHazardPtrCount * nMaxThreadCount </tt>.
1291 size_t nHazardPtrCount = 0, ///< Hazard pointer count per thread
1292 size_t nMaxThreadCount = 0, ///< Max count of simultaneous working thread in your application
1293 size_t nMaxRetiredPtrCount = 0, ///< Capacity of the array of retired objects for the thread
1294 scan_type nScanType = scan_type::inplace ///< Scan type (see \p scan_type enum)
1300 nMaxRetiredPtrCount,
1301 static_cast<hp::scan_type>(nScanType)
1305 /// Terminates GC singleton
1307 The destructor destroys %HP global object. After calling of this function you may \b NOT
1308 use CDS data structures based on \p %cds::gc::HP.
1309 Usually, %HP object is destroyed at the end of your \p main().
1313 hp::smr::destruct( true );
1316 /// Checks that required hazard pointer count \p nCountNeeded is less or equal then max hazard pointer count
1318 If <tt> nRequiredCount > get_hazard_ptr_count()</tt> then the exception \p not_enought_hazard_ptr is thrown
1320 static void check_available_guards( size_t nCountNeeded )
1322 hp::smr::check_hazard_ptr_count( nCountNeeded );
1325 /// Set memory management functions
1327 @note This function may be called <b>BEFORE</b> creating an instance
1328 of Hazard Pointer SMR
1330 SMR object allocates some memory for thread-specific data and for
1331 creating SMR object.
1332 By default, a standard \p new and \p delete operators are used for this.
1334 static void set_memory_allocator(
1335 void* ( *alloc_func )( size_t size ), ///< \p malloc() function
1336 void( *free_func )( void * p ) ///< \p free() function
1339 hp::smr::set_memory_allocator( alloc_func, free_func );
1342 /// Returns max Hazard Pointer count
1343 static size_t max_hazard_count()
1345 return hp::smr::instance().get_hazard_ptr_count();
1348 /// Returns max count of thread
1349 static size_t max_thread_count()
1351 return hp::smr::instance().get_max_thread_count();
1354 /// Returns capacity of retired pointer array
1355 static size_t retired_array_capacity()
1357 return hp::smr::instance().get_max_retired_ptr_count();
1360 /// Retire pointer \p p with function \p func
1362 The function places pointer \p p to array of pointers ready for removing.
1363 (so called retired pointer array). The pointer can be safely removed when no hazard pointer points to it.
1364 \p func is a disposer: when \p p can be safely removed, \p func is called.
1366 template <typename T>
1367 static void retire( T * p, void( *func )( T * ))
1369 hp::thread_data* rec = hp::smr::tls();
1370 if ( !rec->retired_.push( hp::retired_ptr( p, func )))
1371 hp::smr::instance().scan( rec );
1374 /// Retire pointer \p p with functor of type \p Disposer
1376 The function places pointer \p p to array of pointers ready for removing.
1377 (so called retired pointer array). The pointer can be safely removed when no hazard pointer points to it.
1379 Deleting the pointer is an invocation of some object of type \p Disposer; the interface of \p Disposer is:
1381 template <typename T>
1383 void operator()( T * p ) ; // disposing operator
1386 Since the functor call can happen at any time after \p retire() call, additional restrictions are imposed to \p Disposer type:
1387 - it should be stateless functor
1388 - it should be default-constructible
1389 - the result of functor call with argument \p p should not depend on where the functor will be called.
1392 Operator \p delete functor:
1394 template <typename T>
1396 void operator ()( T * p ) {
1401 // How to call HP::retire method
1404 // ... use p in lock-free manner
1406 cds::gc::HP::retire<disposer>( p ) ; // place p to retired pointer array of HP GC
1409 Functor based on \p std::allocator :
1411 template <typename Alloc = std::allocator<int> >
1413 template <typename T>
1414 void operator()( T * p ) {
1415 typedef typename Alloc::templare rebind<T>::other alloc_t;
1418 a.deallocate( p, 1 );
1423 template <class Disposer, typename T>
1424 static void retire( T * p )
1426 if ( !hp::smr::tls()->retired_.push( hp::retired_ptr( p, cds::details::static_functor<Disposer, T>::call )))
1430 /// Get current scan strategy
1431 static scan_type getScanType()
1433 return static_cast<scan_type>( hp::smr::instance().get_scan_type());
1436 /// Checks if Hazard Pointer GC is constructed and may be used
1437 static bool isUsed()
1439 return hp::smr::isUsed();
1442 /// Forces SMR call for current thread
1444 Usually, this function should not be called directly.
1448 hp::smr::instance().scan( hp::smr::tls());
1451 /// Synonym for \p scan()
1452 static void force_dispose()
1457 /// Returns internal statistics
1459 The function clears \p st before gathering statistics.
1461 @note Internal statistics is available only if you compile
1462 \p libcds and your program with \p -DCDS_ENABLE_HPSTAT key.
1464 static void statistics( stat& st )
1466 hp::smr::instance().statistics( st );
1469 /// Returns post-mortem statistics
1471 Post-mortem statistics is gathered in the \p %HP object destructor
1472 and can be accessible after destructing the global \p %HP object.
1474 @note Internal statistics is available only if you compile
1475 \p libcds and your program with \p -DCDS_ENABLE_HPSTAT key.
1483 // Initialize HP SMR
1486 // deal with HP-based data structured
1490 // HP object destroyed
1491 // Get total post-mortem statistics
1492 cds::gc::HP::stat const& st = cds::gc::HP::postmortem_statistics();
1494 printf( "HP statistics:\n"
1495 " thread count = %llu\n"
1496 " guard allocated = %llu\n"
1497 " guard freed = %llu\n"
1498 " retired data count = %llu\n"
1499 " free data count = %llu\n"
1500 " scan() call count = %llu\n"
1501 " help_scan() call count = %llu\n",
1502 st.thread_rec_count,
1503 st.guard_allocated, st.guard_freed,
1504 st.retired_count, st.free_count,
1505 st.scan_count, st.help_scan_count
1512 static stat const& postmortem_statistics();
1515 }} // namespace cds::gc
1517 #endif // #ifndef CDSLIB_GC_HP_SMR_H