Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-18 08:47:54

0001 //  lock-free queue from
0002 //  Michael, M. M. and Scott, M. L.,
0003 //  "simple, fast and practical non-blocking and blocking concurrent queue algorithms"
0004 //
0005 //  Copyright (C) 2008-2013 Tim Blechmann
0006 //
0007 //  Distributed under the Boost Software License, Version 1.0. (See
0008 //  accompanying file LICENSE_1_0.txt or copy at
0009 //  http://www.boost.org/LICENSE_1_0.txt)
0010 
0011 #ifndef BOOST_LOCKFREE_FIFO_HPP_INCLUDED
0012 #define BOOST_LOCKFREE_FIFO_HPP_INCLUDED
0013 
0014 #include <boost/config.hpp>
0015 #ifdef BOOST_HAS_PRAGMA_ONCE
0016 #    pragma once
0017 #endif
0018 
0019 #include <boost/assert.hpp>
0020 #include <boost/core/allocator_access.hpp>
0021 #include <boost/parameter/optional.hpp>
0022 #include <boost/parameter/parameters.hpp>
0023 #include <boost/static_assert.hpp>
0024 
0025 #include <boost/lockfree/detail/atomic.hpp>
0026 #include <boost/lockfree/detail/copy_payload.hpp>
0027 #include <boost/lockfree/detail/freelist.hpp>
0028 #include <boost/lockfree/detail/parameter.hpp>
0029 #include <boost/lockfree/detail/tagged_ptr.hpp>
0030 #include <boost/lockfree/detail/uses_optional.hpp>
0031 #include <boost/lockfree/lockfree_forward.hpp>
0032 
0033 
0034 #if defined( _MSC_VER )
0035 #    pragma warning( push )
0036 #    pragma warning( disable : 4324 ) // structure was padded due to __declspec(align())
0037 #endif
0038 
0039 #if defined( BOOST_INTEL ) && ( BOOST_INTEL_CXX_VERSION > 1000 )
0040 #    pragma warning( push )
0041 #    pragma warning( disable : 488 ) // template parameter unused in declaring parameter types,
0042                                      // gets erronously triggered the queue constructor which
0043                                      // takes an allocator of another type and rebinds it
0044 #endif
0045 
0046 
0047 namespace boost { namespace lockfree {
0048 
0049 #ifndef BOOST_DOXYGEN_INVOKED
0050 namespace detail {
0051 
0052 typedef parameter::parameters< boost::parameter::optional< tag::allocator >, boost::parameter::optional< tag::capacity > >
0053     queue_signature;
0054 
0055 } /* namespace detail */
0056 #endif
0057 
0058 
0059 /** The queue class provides a multi-writer/multi-reader queue, pushing and popping is lock-free,
0060  *  construction/destruction has to be synchronized. It uses a freelist for memory management,
0061  *  freed nodes are pushed to the freelist and not returned to the OS before the queue is destroyed.
0062  *
0063  *  \b Policies:
0064  *  - \ref boost::lockfree::fixed_sized, defaults to \c boost::lockfree::fixed_sized<false> \n
0065  *    Can be used to completely disable dynamic memory allocations during push in order to ensure lockfree behavior. \n
0066  *    If the data structure is configured as fixed-sized, the internal nodes are stored inside an array and they are
0067  * addressed by array indexing. This limits the possible size of the queue to the number of elements that can be
0068  * addressed by the index type (usually 2**16-2), but on platforms that lack double-width compare-and-exchange
0069  * instructions, this is the best way to achieve lock-freedom.
0070  *
0071  *  - \ref boost::lockfree::capacity, optional \n
0072  *    If this template argument is passed to the options, the size of the queue is set at compile-time.\n
0073  *    This option implies \c fixed_sized<true>
0074  *
0075  *  - \ref boost::lockfree::allocator, defaults to \c boost::lockfree::allocator<std::allocator<void>> \n
0076  *    Specifies the allocator that is used for the internal freelist
0077  *
0078  *  \b Requirements:
0079  *   - T must have a copy constructor
0080  *   - T must have a trivial assignment operator
0081  *   - T must have a trivial destructor
0082  *
0083  * */
0084 template < typename T, typename... Options >
0085 #if !defined( BOOST_NO_CXX20_HDR_CONCEPTS )
0086     requires( std::is_copy_assignable_v< T >,
0087               std::is_trivially_assignable_v< T&, T >,
0088               std::is_trivially_destructible_v< T > )
0089 #endif
0090 class queue
0091 {
0092 private:
0093 #ifndef BOOST_DOXYGEN_INVOKED
0094 
0095     BOOST_STATIC_ASSERT( ( std::is_trivially_destructible< T >::value ) );
0096     BOOST_STATIC_ASSERT( ( std::is_trivially_assignable< T&, T >::value ) );
0097 
0098     typedef typename detail::queue_signature::bind< Options... >::type bound_args;
0099 
0100     static constexpr bool   has_capacity = detail::extract_capacity< bound_args >::has_capacity;
0101     static constexpr size_t capacity
0102         = detail::extract_capacity< bound_args >::capacity + 1; // the queue uses one dummy node
0103     static constexpr bool fixed_sized        = detail::extract_fixed_sized< bound_args >::value;
0104     static constexpr bool node_based         = !( has_capacity || fixed_sized );
0105     static constexpr bool compile_time_sized = has_capacity;
0106 
0107     struct alignas( detail::cacheline_bytes ) node
0108     {
0109         typedef typename detail::select_tagged_handle< node, node_based >::tagged_handle_type tagged_node_handle;
0110         typedef typename detail::select_tagged_handle< node, node_based >::handle_type        handle_type;
0111 
0112         node( T const& v, handle_type null_handle ) :
0113             data( v )
0114         {
0115             /* increment tag to avoid ABA problem */
0116             tagged_node_handle old_next = next.load( memory_order_relaxed );
0117             tagged_node_handle new_next( null_handle, old_next.get_next_tag() );
0118             next.store( new_next, memory_order_release );
0119         }
0120 
0121         node( handle_type null_handle ) :
0122             next( tagged_node_handle( null_handle, 0 ) )
0123         {}
0124 
0125         node( void )
0126         {}
0127 
0128         atomic< tagged_node_handle > next;
0129         T                            data;
0130     };
0131 
0132     typedef detail::extract_allocator_t< bound_args, node >                                              node_allocator;
0133     typedef detail::select_freelist_t< node, node_allocator, compile_time_sized, fixed_sized, capacity > pool_t;
0134     typedef typename pool_t::tagged_node_handle                                    tagged_node_handle;
0135     typedef typename detail::select_tagged_handle< node, node_based >::handle_type handle_type;
0136 
0137     void initialize( void )
0138     {
0139         node*              n = pool.template construct< true, false >( pool.null_handle() );
0140         tagged_node_handle dummy_node( pool.get_handle( n ), 0 );
0141         head_.store( dummy_node, memory_order_relaxed );
0142         tail_.store( dummy_node, memory_order_release );
0143     }
0144 
0145     struct implementation_defined
0146     {
0147         typedef node_allocator allocator;
0148         typedef std::size_t    size_type;
0149     };
0150 
0151 #endif
0152 
0153 public:
0154     typedef T                                          value_type;
0155     typedef typename implementation_defined::allocator allocator;
0156     typedef typename implementation_defined::size_type size_type;
0157 
0158     /**
0159      * \return true, if implementation is lock-free.
0160      *
0161      * \warning It only checks, if the queue head and tail nodes and the freelist can be modified in a lock-free manner.
0162      *       On most platforms, the whole implementation is lock-free, if this is true. Using c++0x-style atomics, there
0163      * is no possibility to provide a completely accurate implementation, because one would need to test every internal
0164      *       node, which is impossible if further nodes will be allocated from the operating system.
0165      * */
0166     bool is_lock_free( void ) const
0167     {
0168         return head_.is_lock_free() && tail_.is_lock_free() && pool.is_lock_free();
0169     }
0170 
0171     /** Construct a fixed-sized queue
0172      *
0173      *  \pre Must specify a capacity<> argument
0174      * */
0175     queue( void )
0176 #if !defined( BOOST_NO_CXX20_HDR_CONCEPTS )
0177         requires( has_capacity )
0178 #endif
0179         :
0180         head_( tagged_node_handle( 0, 0 ) ),
0181         tail_( tagged_node_handle( 0, 0 ) ),
0182         pool( node_allocator(), capacity )
0183     {
0184         // Don't use BOOST_STATIC_ASSERT() here since it will be evaluated when compiling
0185         // this function and this function may be compiled even when it isn't being used.
0186         BOOST_ASSERT( has_capacity );
0187         initialize();
0188     }
0189 
0190     /** Construct a fixed-sized queue with a custom allocator
0191      *
0192      *  \pre Must specify a capacity<> argument
0193      * */
0194     template < typename U, typename Enabler = std::enable_if< has_capacity > >
0195     explicit queue( typename boost::allocator_rebind< node_allocator, U >::type const& alloc ) :
0196         head_( tagged_node_handle( 0, 0 ) ),
0197         tail_( tagged_node_handle( 0, 0 ) ),
0198         pool( alloc, capacity )
0199     {
0200         initialize();
0201     }
0202 
0203     /** Construct a fixed-sized queue with a custom allocator
0204      *
0205      *  \pre Must specify a capacity<> argument
0206      * */
0207     template < typename Enabler = std::enable_if< has_capacity > >
0208     explicit queue( allocator const& alloc ) :
0209         head_( tagged_node_handle( 0, 0 ) ),
0210         tail_( tagged_node_handle( 0, 0 ) ),
0211         pool( alloc, capacity )
0212     {
0213         initialize();
0214     }
0215 
0216     /** Construct a variable-sized queue
0217      *
0218      *  Allocate n nodes initially for the freelist
0219      *
0220      *  \pre Must \b not specify a capacity<> argument
0221      * */
0222     template < typename Enabler = std::enable_if< !has_capacity > >
0223     explicit queue( size_type n ) :
0224         head_( tagged_node_handle( 0, 0 ) ),
0225         tail_( tagged_node_handle( 0, 0 ) ),
0226         pool( node_allocator(), n + 1 )
0227     {
0228         initialize();
0229     }
0230 
0231     /** Construct a variable-sized queue with a custom allocator
0232      *
0233      *  Allocate n nodes initially for the freelist
0234      *
0235      *  \pre Must \b not specify a capacity<> argument
0236      * */
0237     template < typename U, typename Enabler = std::enable_if< !has_capacity > >
0238     queue( size_type n, typename boost::allocator_rebind< node_allocator, U >::type const& alloc ) :
0239         head_( tagged_node_handle( 0, 0 ) ),
0240         tail_( tagged_node_handle( 0, 0 ) ),
0241         pool( alloc, n + 1 )
0242     {
0243         initialize();
0244     }
0245 
0246     /** Construct a variable-sized queue with a custom allocator
0247      *
0248      *  Allocate n nodes initially for the freelist
0249      *
0250      *  \pre Must \b not specify a capacity<> argument
0251      * */
0252     template < typename Enabler = std::enable_if< !has_capacity > >
0253     queue( size_type n, allocator const& alloc ) :
0254         head_( tagged_node_handle( 0, 0 ) ),
0255         tail_( tagged_node_handle( 0, 0 ) ),
0256         pool( alloc, n + 1 )
0257     {
0258         initialize();
0259     }
0260 
0261     queue( const queue& )            = delete;
0262     queue& operator=( const queue& ) = delete;
0263     queue( queue&& )                 = delete;
0264     queue& operator=( queue&& )      = delete;
0265 
0266     /** \copydoc boost::lockfree::stack::reserve
0267      * */
0268     void reserve( size_type n )
0269     {
0270         pool.template reserve< true >( n );
0271     }
0272 
0273     /** \copydoc boost::lockfree::stack::reserve_unsafe
0274      * */
0275     void reserve_unsafe( size_type n )
0276     {
0277         pool.template reserve< false >( n );
0278     }
0279 
0280     /** Destroys queue, free all nodes from freelist.
0281      * */
0282     ~queue( void )
0283     {
0284         consume_all( []( const T& ) {} );
0285 
0286         pool.template destruct< false >( head_.load( memory_order_relaxed ) );
0287     }
0288 
0289     /** Check if the queue is empty
0290      *
0291      * \return true, if the queue is empty, false otherwise
0292      * \note The result is only accurate, if no other thread modifies the queue. Therefore it is rarely practical to use
0293      * this value in program logic.
0294      * */
0295     bool empty( void ) const
0296     {
0297         return pool.get_handle( head_.load() ) == pool.get_handle( tail_.load() );
0298     }
0299 
0300     /** Pushes object t to the queue.
0301      *
0302      * \post object will be pushed to the queue, if internal node can be allocated
0303      * \returns true, if the push operation is successful.
0304      *
0305      * \note Thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will
0306      * be allocated from the OS. This may not be lock-free.
0307      * */
0308     bool push( const T& t )
0309     {
0310         return do_push< false >( t );
0311     }
0312 
0313     /// \copydoc boost::lockfree::queue::push(const T & t)
0314     bool push( T&& t )
0315     {
0316         return do_push< false >( std::forward< T >( t ) );
0317     }
0318 
0319     /** Pushes object t to the queue.
0320      *
0321      * \post object will be pushed to the queue, if internal node can be allocated
0322      * \returns true, if the push operation is successful.
0323      *
0324      * \note Thread-safe and non-blocking. If internal memory pool is exhausted, operation will fail
0325      * \throws if memory allocator throws
0326      * */
0327     bool bounded_push( const T& t )
0328     {
0329         return do_push< true >( t );
0330     }
0331 
0332     /// \copydoc boost::lockfree::queue::bounded_push(const T & t)
0333     bool bounded_push( T&& t )
0334     {
0335         return do_push< true >( std::forward< T >( t ) );
0336     }
0337 
0338 
0339 private:
0340 #ifndef BOOST_DOXYGEN_INVOKED
0341     template < bool Bounded >
0342     bool do_push( T&& t )
0343     {
0344         node* n = pool.template construct< true, Bounded >( std::forward< T >( t ), pool.null_handle() );
0345         return do_push_node( n );
0346     }
0347 
0348     template < bool Bounded >
0349     bool do_push( T const& t )
0350     {
0351         node* n = pool.template construct< true, Bounded >( t, pool.null_handle() );
0352         return do_push_node( n );
0353     }
0354 
0355     bool do_push_node( node* n )
0356     {
0357         handle_type node_handle = pool.get_handle( n );
0358 
0359         if ( n == NULL )
0360             return false;
0361 
0362         for ( ;; ) {
0363             tagged_node_handle tail      = tail_.load( memory_order_acquire );
0364             node*              tail_node = pool.get_pointer( tail );
0365             tagged_node_handle next      = tail_node->next.load( memory_order_acquire );
0366             node*              next_ptr  = pool.get_pointer( next );
0367 
0368             tagged_node_handle tail2 = tail_.load( memory_order_acquire );
0369             if ( BOOST_LIKELY( tail == tail2 ) ) {
0370                 if ( next_ptr == 0 ) {
0371                     tagged_node_handle new_tail_next( node_handle, next.get_next_tag() );
0372                     if ( tail_node->next.compare_exchange_weak( next, new_tail_next ) ) {
0373                         tagged_node_handle new_tail( node_handle, tail.get_next_tag() );
0374                         tail_.compare_exchange_strong( tail, new_tail );
0375                         return true;
0376                     }
0377                 } else {
0378                     tagged_node_handle new_tail( pool.get_handle( next_ptr ), tail.get_next_tag() );
0379                     tail_.compare_exchange_strong( tail, new_tail );
0380                 }
0381             }
0382         }
0383     }
0384 
0385 #endif
0386 
0387 public:
0388     /** Pushes object t to the queue.
0389      *
0390      * \post object will be pushed to the queue, if internal node can be allocated
0391      * \returns true, if the push operation is successful.
0392      *
0393      * \note Not Thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node
0394      * will be allocated from the OS. This may not be lock-free. \throws if memory allocator throws
0395      * */
0396     bool unsynchronized_push( T&& t )
0397     {
0398         node* n = pool.template construct< false, false >( std::forward< T >( t ), pool.null_handle() );
0399 
0400         if ( n == NULL )
0401             return false;
0402 
0403         for ( ;; ) {
0404             tagged_node_handle tail     = tail_.load( memory_order_relaxed );
0405             tagged_node_handle next     = tail->next.load( memory_order_relaxed );
0406             node*              next_ptr = next.get_ptr();
0407 
0408             if ( next_ptr == 0 ) {
0409                 tail->next.store( tagged_node_handle( n, next.get_next_tag() ), memory_order_relaxed );
0410                 tail_.store( tagged_node_handle( n, tail.get_next_tag() ), memory_order_relaxed );
0411                 return true;
0412             } else
0413                 tail_.store( tagged_node_handle( next_ptr, tail.get_next_tag() ), memory_order_relaxed );
0414         }
0415     }
0416 
0417     /** Pops object from queue.
0418      *
0419      * \post if pop operation is successful, object will be copied to ret.
0420      * \returns true, if the pop operation is successful, false if queue was empty.
0421      *
0422      * \note Thread-safe and non-blocking. Might modify return argument even if operation fails.
0423      * */
0424     bool pop( T& ret )
0425     {
0426         return pop< T >( ret );
0427     }
0428 
0429     /** Pops object from queue.
0430      *
0431      * \pre type U must be constructible by T and copyable, or T must be convertible to U
0432      * \post if pop operation is successful, object will be copied to ret.
0433      * \returns true, if the pop operation is successful, false if queue was empty.
0434      *
0435      * \note Thread-safe and non-blocking. Might modify return argument even if operation fails.
0436      * */
0437     template < typename U >
0438     bool pop( U& ret )
0439     {
0440         for ( ;; ) {
0441             tagged_node_handle head     = head_.load( memory_order_acquire );
0442             node*              head_ptr = pool.get_pointer( head );
0443 
0444             tagged_node_handle tail     = tail_.load( memory_order_acquire );
0445             tagged_node_handle next     = head_ptr->next.load( memory_order_acquire );
0446             node*              next_ptr = pool.get_pointer( next );
0447 
0448             tagged_node_handle head2 = head_.load( memory_order_acquire );
0449             if ( BOOST_LIKELY( head == head2 ) ) {
0450                 if ( pool.get_handle( head ) == pool.get_handle( tail ) ) {
0451                     if ( next_ptr == 0 )
0452                         return false;
0453 
0454                     tagged_node_handle new_tail( pool.get_handle( next ), tail.get_next_tag() );
0455                     tail_.compare_exchange_strong( tail, new_tail );
0456 
0457                 } else {
0458                     if ( next_ptr == 0 )
0459                         /* this check is not part of the original algorithm as published by michael and scott
0460                          *
0461                          * however we reuse the tagged_ptr part for the freelist and clear the next part during node
0462                          * allocation. we can observe a null-pointer here.
0463                          * */
0464                         continue;
0465                     detail::copy_payload( next_ptr->data, ret );
0466 
0467                     tagged_node_handle new_head( pool.get_handle( next ), head.get_next_tag() );
0468                     if ( head_.compare_exchange_weak( head, new_head ) ) {
0469                         pool.template destruct< true >( head );
0470                         return true;
0471                     }
0472                 }
0473             }
0474         }
0475     }
0476 
0477 #if !defined( BOOST_NO_CXX17_HDR_OPTIONAL ) || defined( BOOST_DOXYGEN_INVOKED )
0478     /** Pops object from queue, returning a std::optional<>
0479      *
0480      * \returns `std::optional` with value if successful, `std::nullopt` if queue is empty.
0481      *
0482      * \note Thread-safe and non-blocking
0483      *
0484      * */
0485     std::optional< T > pop( uses_optional_t )
0486     {
0487         T to_dequeue;
0488         if ( pop( to_dequeue ) )
0489             return to_dequeue;
0490         else
0491             return std::nullopt;
0492     }
0493 
0494     /** Pops object from queue, returning a std::optional<>
0495      *
0496      * \pre type T must be convertible to U
0497      * \returns `std::optional` with value if successful, `std::nullopt` if queue is empty.
0498      *
0499      * \note Thread-safe and non-blocking
0500      *
0501      * */
0502     template < typename U >
0503     std::optional< U > pop( uses_optional_t )
0504     {
0505         U to_dequeue;
0506         if ( pop( to_dequeue ) )
0507             return to_dequeue;
0508         else
0509             return std::nullopt;
0510     }
0511 #endif
0512 
0513     /** Pops object from queue.
0514      *
0515      * \post if pop operation is successful, object will be copied to ret.
0516      * \returns true, if the pop operation is successful, false if queue was empty.
0517      *
0518      * \note Not thread-safe, but non-blocking. Might modify return argument even if operation fails.
0519      *
0520      * */
0521     bool unsynchronized_pop( T& ret )
0522     {
0523         return unsynchronized_pop< T >( ret );
0524     }
0525 
0526     /** Pops object from queue.
0527      *
0528      * \pre type U must be constructible by T and copyable, or T must be convertible to U
0529      * \post if pop operation is successful, object will be copied to ret.
0530      *
0531      * \returns true, if the pop operation is successful, false if queue was empty.
0532      *
0533      * \note Not thread-safe, but non-blocking. Might modify return argument even if operation fails.
0534      *
0535      * */
0536     template < typename U >
0537     bool unsynchronized_pop( U& ret )
0538     {
0539         for ( ;; ) {
0540             tagged_node_handle head     = head_.load( memory_order_relaxed );
0541             node*              head_ptr = pool.get_pointer( head );
0542             tagged_node_handle tail     = tail_.load( memory_order_relaxed );
0543             tagged_node_handle next     = head_ptr->next.load( memory_order_relaxed );
0544             node*              next_ptr = pool.get_pointer( next );
0545 
0546             if ( pool.get_handle( head ) == pool.get_handle( tail ) ) {
0547                 if ( next_ptr == 0 )
0548                     return false;
0549 
0550                 tagged_node_handle new_tail( pool.get_handle( next ), tail.get_next_tag() );
0551                 tail_.store( new_tail );
0552             } else {
0553                 if ( next_ptr == 0 )
0554                     /* this check is not part of the original algorithm as published by michael and scott
0555                      *
0556                      * however we reuse the tagged_ptr part for the freelist and clear the next part during node
0557                      * allocation. we can observe a null-pointer here.
0558                      * */
0559                     continue;
0560                 detail::copy_payload( next_ptr->data, ret );
0561                 tagged_node_handle new_head( pool.get_handle( next ), head.get_next_tag() );
0562                 head_.store( new_head );
0563                 pool.template destruct< false >( head );
0564                 return true;
0565             }
0566         }
0567     }
0568 
0569     /** consumes one element via a functor
0570      *
0571      *  pops one element from the queue and applies the functor on this object
0572      *
0573      * \returns true, if one element was consumed
0574      *
0575      * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
0576      * */
0577     template < typename Functor >
0578     bool consume_one( Functor&& f )
0579     {
0580         T    element;
0581         bool success = pop( element );
0582         if ( success )
0583             f( std::move( element ) );
0584 
0585         return success;
0586     }
0587 
0588     /** consumes all elements via a functor
0589      *
0590      * sequentially pops all elements from the queue and applies the functor on each object
0591      *
0592      * \returns number of elements that are consumed
0593      *
0594      * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
0595      * */
0596     template < typename Functor >
0597     size_t consume_all( Functor&& f )
0598     {
0599         size_t element_count = 0;
0600         while ( consume_one( f ) )
0601             element_count += 1;
0602 
0603         return element_count;
0604     }
0605 
0606 private:
0607 #ifndef BOOST_DOXYGEN_INVOKED
0608     atomic< tagged_node_handle > head_;
0609     static constexpr int         padding_size = detail::cacheline_bytes - sizeof( tagged_node_handle );
0610     char                         padding1[ padding_size ];
0611     atomic< tagged_node_handle > tail_;
0612     char                         padding2[ padding_size ];
0613 
0614     pool_t pool;
0615 #endif
0616 };
0617 
0618 }} // namespace boost::lockfree
0619 
0620 #if defined( BOOST_INTEL ) && ( BOOST_INTEL_CXX_VERSION > 1000 )
0621 #    pragma warning( pop )
0622 #endif
0623 
0624 #if defined( _MSC_VER )
0625 #    pragma warning( pop )
0626 #endif
0627 
0628 #endif /* BOOST_LOCKFREE_FIFO_HPP_INCLUDED */