optimistic_queue.h 15 KB

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