4ee76da3a3ef98fd57e6507fd9c86bc5ea5dbae8
[libcds.git] / cds / container / optimistic_queue.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_CONTAINER_OPTIMISTIC_QUEUE_H
4 #define __CDS_CONTAINER_OPTIMISTIC_QUEUE_H
5
6 #include <memory>
7 #include <cds/intrusive/optimistic_queue.h>
8 #include <cds/container/details/base.h>
9 #include <cds/ref.h>
10 #include <cds/details/trivial_assign.h>
11
12 namespace cds { namespace container {
13
14     //@cond
15     namespace details {
16         template <typename GC, typename T, typename... Options>
17         struct make_optimistic_queue
18         {
19             typedef GC gc;
20             typedef T value_type;
21
22             struct default_options {
23                 typedef cds::backoff::empty     back_off;
24                 typedef CDS_DEFAULT_ALLOCATOR   allocator;
25                 typedef atomicity::empty_item_counter item_counter;
26                 typedef intrusive::optimistic_queue::dummy_stat stat;
27                 typedef opt::v::relaxed_ordering    memory_model;
28                 enum { alignment = opt::cache_line_alignment };
29             };
30
31             typedef typename opt::make_options<
32                 typename cds::opt::find_type_traits< default_options, Options... >::type
33                 ,Options...
34             >::type   options;
35
36             struct node_type: public intrusive::optimistic_queue::node< gc >
37             {
38                 value_type  m_value;
39
40                 node_type( value_type const& val )
41                     : m_value( val )
42                 {}
43
44                 template <typename... Args>
45                 node_type( Args&&... args )
46                     : m_value( std::forward<Args>(args)...)
47                 {}
48             };
49
50             typedef typename options::allocator::template rebind<node_type>::other allocator_type;
51             typedef cds::details::Allocator< node_type, allocator_type >           cxx_allocator;
52
53             struct node_deallocator
54             {
55                 void operator ()( node_type * pNode )
56                 {
57                     cxx_allocator().Delete( pNode );
58                 }
59             };
60
61             typedef intrusive::OptimisticQueue< gc,
62                 node_type
63                 ,intrusive::opt::hook<
64                     intrusive::optimistic_queue::base_hook< opt::gc<gc> >
65                 >
66                 ,opt::back_off< typename options::back_off >
67                 ,intrusive::opt::disposer< node_deallocator >
68                 ,opt::item_counter< typename options::item_counter >
69                 ,opt::stat< typename options::stat >
70                 ,opt::alignment< options::alignment >
71                 ,opt::memory_model< typename options::memory_model >
72             >   type;
73         };
74     }   // namespace details
75     //@endcond
76
77     /// Optimistic queue
78     /** @ingroup cds_nonintrusive_queue
79         Implementation of Ladan-Mozes & Shavit optimistic queue algorithm.
80
81         \par Source:
82             [2008] Edya Ladan-Mozes, Nir Shavit "An Optimistic Approach to Lock-Free FIFO Queues"
83
84         Template arguments:
85         - \p GC - garbage collector type: gc::HP, gc::PTB. Note that gc::HRC is <b>not</b> supported
86         - \p T - type to be stored in the queue
87         - \p Options - options
88
89         \p Options are:
90         - opt::back_off - back-off strategy used. If the option is not specified, the cds::backoff::empty is used.
91         - opt::allocator - allocator (like \p std::allocator) used for nodes allocation. Default is \ref CDS_DEFAULT_ALLOCATOR
92         - opt::item_counter - the type of item counting feature. Default is \ref atomicity::empty_item_counter
93         - opt::stat - the type to gather internal statistics for debugging and profiling purposes.
94             Possible option value are: intrusive::optimistic_queue::stat, intrusive::optimistic_queue::dummy_stat (the default),
95             user-provided class that supports intrusive::optimistic_queue::stat interface.
96             Generic option intrusive::queue_stat and intrusive::queue_dummy_stat are acceptable too, however,
97             they will be automatically converted to intrusive::optimistic_queue::stat and intrusive::optimistic_queue::dummy_stat
98             respectively.
99         - opt::alignment - the alignment for internal queue data. Default is opt::cache_line_alignment
100         - opt::memory_model - C++ memory ordering model. Can be opt::v::relaxed_ordering (relaxed memory model, the default)
101             or opt::v::sequential_consistent (sequentially consisnent memory model).
102
103         <b>Warning</b> gc::HRC is not supported for this implementation.
104     */
105     template <typename GC, typename T, typename... Options>
106     class OptimisticQueue:
107 #ifdef CDS_DOXYGEN_INVOKED
108         intrusive::OptimisticQueue< GC, intrusive::optimistic_queue::node< T >, Options... >
109 #else
110         details::make_optimistic_queue< GC, T, Options... >::type
111 #endif
112     {
113         //@cond
114         typedef details::make_optimistic_queue< GC, T, Options... > options;
115         typedef typename options::type base_class;
116         //@endcond
117
118     public:
119         /// Rebind template arguments
120         template <typename GC2, typename T2, typename... Options2>
121         struct rebind {
122             typedef OptimisticQueue< GC2, T2, Options2...> other   ;   ///< Rebinding result
123         };
124
125     public:
126         typedef T value_type ; ///< Value type stored in the stack
127
128         typedef typename base_class::gc                 gc              ; ///< Garbage collector used
129         typedef typename base_class::back_off           back_off        ; ///< Back-off strategy used
130         typedef typename options::allocator_type        allocator_type  ; ///< Allocator type used for allocate/deallocate the nodes
131         typedef typename options::options::item_counter item_counter    ; ///< Item counting policy used
132         typedef typename options::options::stat         stat            ; ///< Internal statistics policy used
133         typedef typename base_class::memory_model       memory_model    ; ///< Memory ordering. See cds::opt::memory_model option
134
135         static CDS_CONSTEXPR_CONST size_t c_nHazardPtrCount = base_class::c_nHazardPtrCount; ///< Count of hazard pointer required for the algorithm
136
137     protected:
138         typedef typename options::node_type  node_type   ;   ///< queue node type (derived from intrusive::optimistic_queue::node)
139
140         //@cond
141         typedef typename options::cxx_allocator     cxx_allocator;
142         typedef typename options::node_deallocator  node_deallocator;   // deallocate node
143         typedef typename base_class::node_traits    node_traits;
144         //@endcond
145
146     protected:
147         ///@cond
148         static node_type * alloc_node()
149         {
150             return cxx_allocator().New();
151         }
152         static node_type * alloc_node( const value_type& val )
153         {
154             return cxx_allocator().New( val );
155         }
156         template <typename... Args>
157         static node_type * alloc_node_move( Args&&... args )
158         {
159             return cxx_allocator().MoveNew( std::forward<Args>( args )... );
160         }
161         static void free_node( node_type * p )
162         {
163             node_deallocator()( p );
164         }
165
166         struct node_disposer {
167             void operator()( node_type * pNode )
168             {
169                 free_node( pNode );
170             }
171         };
172         typedef std::unique_ptr< node_type, node_disposer >     scoped_node_ptr;
173         //@endcond
174
175     public:
176         /// Initializes empty queue
177         OptimisticQueue()
178         {}
179
180         /// Destructor clears the queue
181         ~OptimisticQueue()
182         {}
183
184         /// Returns queue's item count (see \ref intrusive::OptimisticQueue::size for explanation)
185         size_t size() const
186         {
187             return base_class::size();
188         }
189
190         /// Returns reference to internal statistics
191         const stat& statistics() const
192         {
193             return base_class::statistics();
194         }
195
196         /// Enqueues \p val value into the queue.
197         /**
198             The function makes queue node in dynamic memory calling copy constructor for \p val
199             and then it calls intrusive::OptimisticQueue::enqueue.
200             Returns \p true if success, \p false otherwise.
201         */
202         bool enqueue( const value_type& val )
203         {
204             scoped_node_ptr p( alloc_node(val));
205             if ( base_class::enqueue( *p )) {
206                 p.release();
207                 return true;
208             }
209             return false;
210         }
211
212         /// Enqueues \p data to queue using copy functor
213         /**
214             \p Func is a functor called to copy value \p data of type \p Type
215             which may be differ from type \p T stored in the queue.
216             The functor's interface is:
217             \code
218             struct myFunctor {
219                 void operator()(T& dest, SOURCE const& data)
220                 {
221                     // // Code to copy \p data to \p dest
222                     dest = data;
223                 }
224             };
225             \endcode
226             You may use \p boost:ref construction to pass functor \p f by reference.
227
228             <b>Requirements</b> The functor \p Func should not throw any exception.
229         */
230         template <typename Type, typename Func>
231         bool enqueue( const Type& data, Func f  )
232         {
233             scoped_node_ptr p( alloc_node() );
234             unref(f)( p->m_value, data );
235             if ( base_class::enqueue( *p )) {
236                 p.release();
237                 return true;
238             }
239             return false;
240         }
241
242         /// Enqueues data of type \ref value_type constructed with <tt>std::forward<Args>(args)...</tt>
243         template <typename... Args>
244         bool emplace( Args&&... args )
245         {
246             scoped_node_ptr p( alloc_node_move( std::forward<Args>(args)... ));
247             if ( base_class::enqueue( *p )) {
248                 p.release();
249                 return true;
250             }
251             return false;
252         }
253
254         /// Dequeues a value using copy functor
255         /**
256             \p Func is a functor called to copy dequeued value to \p dest of type \p Type
257             which may be differ from type \p T stored in the queue.
258             The functor's interface is:
259             \code
260             struct myFunctor {
261                 void operator()(Type& dest, T const& data)
262                 {
263                     // Code to copy \p data to \p dest
264                     dest = data;
265                 }
266             };
267             \endcode
268             You may use \p boost:ref construction to pass functor \p f by reference.
269
270             <b>Requirements</b> The functor \p Func should not throw any exception.
271         */
272         template <typename Type, typename Func>
273         bool dequeue( Type& dest, Func f )
274         {
275             typename base_class::dequeue_result res;
276             if ( base_class::do_dequeue( res )) {
277                 unref(f)( dest, node_traits::to_value_ptr( *res.pNext )->m_value );
278
279                 base_class::dispose_result( res );
280
281                 return true;
282             }
283             return false;
284         }
285
286         /// Dequeues a value from the queue
287         /**
288             If queue is not empty, the function returns \p true, \p dest contains copy of
289             dequeued value. The assignment operator for type \ref value_type is invoked.
290             If queue is empty, the function returns \p false, \p dest is unchanged.
291         */
292         bool dequeue( value_type& dest )
293         {
294             typedef cds::details::trivial_assign<value_type, value_type> functor;
295             return dequeue( dest, functor() );
296         }
297
298         /// Synonym for \ref enqueue function
299         bool push( const value_type& val )
300         {
301             return enqueue( val );
302         }
303
304         /// Synonym for template version of \ref enqueue function
305         template <typename Type, typename Func>
306         bool push( const Type& data, Func f  )
307         {
308             return enqueue( data, f );
309         }
310
311         /// Synonym for \ref dequeue function
312         bool pop( value_type& dest )
313         {
314             return dequeue( dest );
315         }
316
317         /// Synonym for template version of \ref dequeue function
318         template <typename Type, typename Func>
319         bool pop( Type& dest, Func f )
320         {
321             return dequeue( dest, f );
322         }
323
324         /// Checks if the queue is empty
325         bool empty() const
326         {
327             return base_class::empty();
328         }
329
330         /// Clear the queue
331         /**
332             The function repeatedly calls \ref dequeue until it returns \p nullptr.
333         */
334         void clear()
335         {
336             base_class::clear();
337         }
338     };
339
340 }}  // namespace cds::container
341
342 #endif //#ifndef __CDS_CONTAINER_OPTIMISTIC_QUEUE_H