issue#11: cds: changed __CDS_ guard prefix to CDSLIB_ for all .h files
[libcds.git] / cds / container / msqueue.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_CONTAINER_MSQUEUE_H
4 #define CDSLIB_CONTAINER_MSQUEUE_H
5
6 #include <memory>
7 #include <cds/intrusive/msqueue.h>
8 #include <cds/container/details/base.h>
9
10 namespace cds { namespace container {
11
12     /// MSQueue related definitions
13     /** @ingroup cds_nonintrusive_helper
14     */
15     namespace msqueue {
16         /// Internal statistics
17         template <typename Counter = cds::intrusive::msqueue::stat<>::counter_type >
18         using stat = cds::intrusive::msqueue::stat< Counter >;
19
20         /// Dummy internal statistics
21         typedef cds::intrusive::msqueue::empty_stat empty_stat;
22
23         /// MSQueue default type traits
24         struct traits
25         {
26             /// Node allocator
27             typedef CDS_DEFAULT_ALLOCATOR       allocator;
28
29             /// Back-off strategy
30             typedef cds::backoff::empty         back_off;
31
32             /// Item counting feature; by default, disabled. Use \p cds::atomicity::item_counter to enable item counting
33             typedef atomicity::empty_item_counter   item_counter;
34
35             /// Internal statistics (by default, disabled)
36             /**
37                 Possible option value are: \p msqueue::stat, \p msqueue::empty_stat (the default),
38                 user-provided class that supports \p %msqueue::stat interface.
39             */
40             typedef msqueue::empty_stat         stat;
41
42             /// C++ memory ordering model
43             /**
44                 Can be \p opt::v::relaxed_ordering (relaxed memory model, the default)
45                 or \p opt::v::sequential_consistent (sequentially consisnent memory model).
46             */
47             typedef opt::v::relaxed_ordering    memory_model;
48
49             /// Alignment of internal queue data. Default is \p opt::cache_line_alignment
50             enum { alignment = opt::cache_line_alignment };
51         };
52
53         /// Metafunction converting option list to \p msqueue::traits
54         /**
55             Supported \p Options are:
56             - \p opt::allocator - allocator (like \p std::allocator) used for allocating queue nodes. Default is \ref CDS_DEFAULT_ALLOCATOR
57             - \p opt::back_off - back-off strategy used, default is \p cds::backoff::empty.
58             - \p opt::item_counter - the type of item counting feature. Default is \p cds::atomicity::empty_item_counter (item counting disabled)
59                 To enable item counting use \p cds::atomicity::item_counter
60             - \p opt::stat - the type to gather internal statistics.
61                 Possible statistics types are: \p msqueue::stat, \p msqueue::empty_stat, user-provided class that supports \p %msqueue::stat interface.
62                 Default is \p %msqueue::empty_stat.
63             - \p opt::alignment - the alignment for internal queue data. Default is \p opt::cache_line_alignment
64             - \p opt::memory_model - C++ memory ordering model. Can be \p opt::v::relaxed_ordering (relaxed memory model, the default)
65                 or \p opt::v::sequential_consistent (sequentially consisnent memory model).
66
67             Example: declare \p %MSQueue with item counting and internal statistics
68             \code
69             typedef cds::container::MSQueue< cds::gc::HP, Foo,
70                 typename cds::container::msqueue::make_traits<
71                     cds::opt::item_counter< cds::atomicity::item_counter >,
72                     cds::opt::stat< cds::container::msqueue::stat<> >
73                 >::type
74             > myQueue;
75             \endcode
76         */
77         template <typename... Options>
78         struct make_traits {
79 #   ifdef CDS_DOXYGEN_INVOKED
80             typedef implementation_defined type;   ///< Metafunction result
81 #   else
82             typedef typename cds::opt::make_options<
83                 typename cds::opt::find_type_traits< traits, Options... >::type
84                 , Options...
85             >::type type;
86 #   endif
87         };
88     } // namespace msqueue
89
90     //@cond
91     namespace details {
92         template <typename GC, typename T, typename Traits>
93         struct make_msqueue
94         {
95             typedef GC gc;
96             typedef T value_type;
97             typedef Traits traits;
98
99             struct node_type : public intrusive::msqueue::node< gc >
100             {
101                 value_type  m_value;
102
103                 node_type( value_type const& val )
104                     : m_value( val )
105                 {}
106
107                 template <typename... Args>
108                 node_type( Args&&... args )
109                     : m_value( std::forward<Args>( args )... )
110                 {}
111             };
112
113             typedef typename traits::allocator::template rebind<node_type>::other allocator_type;
114             typedef cds::details::Allocator< node_type, allocator_type >           cxx_allocator;
115
116             struct node_deallocator
117             {
118                 void operator ()( node_type * pNode )
119                 {
120                     cxx_allocator().Delete( pNode );
121                 }
122             };
123
124             struct intrusive_traits : public traits
125             {
126                 typedef cds::intrusive::msqueue::base_hook< cds::opt::gc<gc> > hook;
127                 typedef node_deallocator disposer;
128                 static CDS_CONSTEXPR const cds::intrusive::opt::link_check_type link_checker = cds::intrusive::msqueue::traits::link_checker;
129             };
130
131             typedef intrusive::MSQueue< gc, node_type, intrusive_traits > type;
132         };
133     }
134     //@endcond
135
136     /// Michael & Scott lock-free queue
137     /** @ingroup cds_nonintrusive_queue
138         It is non-intrusive version of Michael & Scott's queue algorithm based on intrusive implementation
139         \p cds::intrusive::MSQueue.
140
141         Template arguments:
142         - \p GC - garbage collector type: \p gc::HP, \p gc::DHP
143         - \p T is a type stored in the queue.
144         - \p Traits - queue traits, default is \p msqueue::traits. You can use \p msqueue::make_traits
145             metafunction to make your traits or just derive your traits from \p %msqueue::traits:
146             \code
147             struct myTraits: public cds::container::msqueue::traits {
148                 typedef cds::intrusive::msqueue::stat<> stat;
149                 typedef cds::atomicity::item_counter    item_counter;
150             };
151             typedef cds::container::MSQueue< cds::gc::HP, Foo, myTraits > myQueue;
152
153             // Equivalent make_traits example:
154             typedef cds::container::MSQueue< cds::gc::HP, Foo,
155                 typename cds::container::msqueue::make_traits<
156                     cds::opt::stat< cds::container::msqueue::stat<> >,
157                     cds::opt::item_counter< cds::atomicity::item_counter >
158                 >::type
159             > myQueue;
160             \endcode
161     */
162     template <typename GC, typename T, typename Traits = cds::container::msqueue::traits>
163     class MSQueue:
164 #ifdef CDS_DOXYGEN_INVOKED
165         private intrusive::MSQueue< GC, cds::intrusive::msqueue::node< T >, Traits >
166 #else
167         private details::make_msqueue< GC, T, Traits >::type
168 #endif
169     {
170         //@cond
171         typedef details::make_msqueue< GC, T, Traits > maker;
172         typedef typename maker::type base_class;
173         //@endcond
174
175     public:
176         /// Rebind template arguments
177         template <typename GC2, typename T2, typename Traits2>
178         struct rebind {
179             typedef MSQueue< GC2, T2, Traits2> other   ;   ///< Rebinding result
180         };
181
182     public:
183         typedef T value_type;   ///< Value type stored in the queue
184         typedef Traits traits;  ///< Queue traits
185
186         typedef typename base_class::gc             gc;             ///< Garbage collector used
187         typedef typename base_class::back_off       back_off;       ///< Back-off strategy used
188         typedef typename maker::allocator_type      allocator_type; ///< Allocator type used for allocate/deallocate the nodes
189         typedef typename base_class::item_counter   item_counter;   ///< Item counting policy used
190         typedef typename base_class::stat           stat;           ///< Internal statistics policy used
191         typedef typename base_class::memory_model   memory_model;   ///< Memory ordering. See cds::opt::memory_model option
192
193     protected:
194         //@cond
195         typedef typename maker::node_type  node_type;   ///< queue node type (derived from \p intrusive::msqueue::node)
196
197         typedef typename maker::cxx_allocator     cxx_allocator;
198         typedef typename maker::node_deallocator  node_deallocator;   // deallocate node
199         typedef typename base_class::node_traits  node_traits;
200         //@endcond
201
202     protected:
203         ///@cond
204         static node_type * alloc_node()
205         {
206             return cxx_allocator().New();
207         }
208         static node_type * alloc_node( value_type const& val )
209         {
210             return cxx_allocator().New( val );
211         }
212         template <typename... Args>
213         static node_type * alloc_node_move( Args&&... args )
214         {
215             return cxx_allocator().MoveNew( std::forward<Args>( args )... );
216         }
217         static void free_node( node_type * p )
218         {
219             node_deallocator()( p );
220         }
221
222         struct node_disposer {
223             void operator()( node_type * pNode )
224             {
225                 free_node( pNode );
226             }
227         };
228         typedef std::unique_ptr< node_type, node_disposer >     scoped_node_ptr;
229         //@endcond
230
231     public:
232         /// Initializes empty queue
233         MSQueue()
234         {}
235
236         /// Destructor clears the queue
237         ~MSQueue()
238         {}
239
240         /// Enqueues \p val value into the queue.
241         /**
242             The function makes queue node in dynamic memory calling copy constructor for \p val
243             and then it calls intrusive::MSQueue::enqueue.
244             Returns \p true if success, \p false otherwise.
245         */
246         bool enqueue( value_type const& val )
247         {
248             scoped_node_ptr p( alloc_node(val) );
249             if ( base_class::enqueue( *p ) ) {
250                 p.release();
251                 return true;
252             }
253             return false;
254         }
255
256         /// Enqueues data to the queue using a functor
257         /**
258             \p Func is a functor called to create node.
259             The functor \p f takes one argument - a reference to a new node of type \ref value_type :
260             \code
261             cds::container::MSQueue< cds::gc::HP, Foo > myQueue;
262             Bar bar;
263             myQueue.enqueue_with( [&bar]( Foo& dest ) { dest = bar; } );
264             \endcode
265         */
266         template <typename Func>
267         bool enqueue_with( Func f )
268         {
269             scoped_node_ptr p( alloc_node() );
270             f( p->m_value );
271             if ( base_class::enqueue( *p )) {
272                 p.release();
273                 return true;
274             }
275             return false;
276         }
277
278         /// Enqueues data of type \ref value_type constructed from <tt>std::forward<Args>(args)...</tt>
279         template <typename... Args>
280         bool emplace( Args&&... args )
281         {
282             scoped_node_ptr p( alloc_node_move( std::forward<Args>( args )... ) );
283             if ( base_class::enqueue( *p ) ) {
284                 p.release();
285                 return true;
286             }
287             return false;
288         }
289
290         /// Synonym for \p enqueue() function
291         bool push( value_type const& val )
292         {
293             return enqueue( val );
294         }
295
296         /// Synonym for \p enqueue_with() function
297         template <typename Func>
298         bool push_with( Func f )
299         {
300             return enqueue_with( f );
301         }
302
303         /// Dequeues a value from the queue
304         /**
305             If queue is not empty, the function returns \p true, \p dest contains copy of
306             dequeued value. The assignment operator for type \ref value_type is invoked.
307             If queue is empty, the function returns \p false, \p dest is unchanged.
308         */
309         bool dequeue( value_type& dest )
310         {
311             return dequeue_with( [&dest]( value_type& src ) { dest = src;  } );
312         }
313
314         /// Dequeues a value using a functor
315         /**
316             \p Func is a functor called to copy dequeued value.
317             The functor takes one argument - a reference to removed node:
318             \code
319             cds:container::MSQueue< cds::gc::HP, Foo > myQueue;
320             Bar bar;
321             myQueue.dequeue_with( [&bar]( Foo& src ) { bar = std::move( src );});
322             \endcode
323             The functor is called only if the queue is not empty.
324         */
325         template <typename Func>
326         bool dequeue_with( Func f )
327         {
328             typename base_class::dequeue_result res;
329             if ( base_class::do_dequeue( res )) {
330                 f( node_traits::to_value_ptr( *res.pNext )->m_value );
331                 base_class::dispose_result( res );
332                 return true;
333             }
334             return false;
335         }
336
337         /// Synonym for \p dequeue() function
338         bool pop( value_type& dest )
339         {
340             return dequeue( dest );
341         }
342
343         /// Synonym for \p dequeue_with() function
344         template <typename Func>
345         bool pop_with( Func f )
346         {
347             return dequeue_with( f );
348         }
349
350         /// Clear the queue
351         /**
352             The function repeatedly calls \ref dequeue until it returns \p nullptr.
353         */
354         void clear()
355         {
356             base_class::clear();
357         }
358
359         /// Checks if the queue is empty
360         bool empty() const
361         {
362             return base_class::empty();
363         }
364
365         /// Returns queue's item count (see \ref intrusive::MSQueue::size for explanation)
366         /** \copydetails cds::intrusive::MSQueue::size()
367         */
368         size_t size() const
369         {
370             return base_class::size();
371         }
372
373         /// Returns reference to internal statistics
374         const stat& statistics() const
375         {
376             return base_class::statistics();
377         }
378     };
379
380 }}  // namespace cds::container
381
382 #endif  // #ifndef CDSLIB_CONTAINER_MSQUEUE_H