treiber_stack.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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_TREIBER_STACK_H
  6. #define CDSLIB_CONTAINER_TREIBER_STACK_H
  7. #include <memory> // unique_ptr
  8. #include <cds/intrusive/treiber_stack.h>
  9. #include <cds/container/details/base.h>
  10. namespace cds { namespace container {
  11. /// TreiberStack related definitions
  12. /** @ingroup cds_nonintrusive_helper
  13. */
  14. namespace treiber_stack {
  15. /// Internal statistics
  16. template <typename Counter = cds::intrusive::treiber_stack::stat<>::counter_type >
  17. using stat = cds::intrusive::treiber_stack::stat< Counter >;
  18. /// Dummy internal statistics
  19. typedef cds::intrusive::treiber_stack::empty_stat empty_stat;
  20. /// TreiberStack default type traits
  21. struct traits
  22. {
  23. /// Back-off strategy
  24. typedef cds::backoff::Default back_off;
  25. /// Node allocator
  26. typedef CDS_DEFAULT_ALLOCATOR allocator;
  27. /// C++ memory ordering model
  28. /**
  29. Can be opt::v::relaxed_ordering (relaxed memory model, the default)
  30. or opt::v::sequential_consistent (sequentially consisnent memory model).
  31. */
  32. typedef opt::v::relaxed_ordering memory_model;
  33. /// Item counting feature; by default, disabled. Use \p cds::atomicity::item_counter to enable item counting
  34. typedef cds::atomicity::empty_item_counter item_counter;
  35. /// Internal statistics (by default, no internal statistics)
  36. /**
  37. Possible types are: \ref treiber_stack::stat, \ref treiber_stack::empty_stat (the default),
  38. user-provided class that supports treiber_stack::stat interface.
  39. */
  40. typedef empty_stat stat;
  41. /** @name Elimination back-off traits
  42. The following traits is used only if elimination enabled
  43. */
  44. ///@{
  45. /// Enable elimination back-off; by default, it is disabled
  46. static constexpr const bool enable_elimination = false;
  47. /// Back-off strategy to wait for elimination, default is cds::backoff::delay<>
  48. typedef cds::backoff::delay<> elimination_backoff;
  49. /// Buffer type for elimination array
  50. /**
  51. Possible types are \p opt::v::initialized_static_buffer, \p opt::v::initialized_dynamic_buffer.
  52. The buffer can be any size: \p Exp2 template parameter of those classes can be \p false.
  53. The size should be selected empirically for your application and hardware, there are no common rules for that.
  54. Default is <tt> %opt::v::initialized_static_buffer< any_type, 4 > </tt>.
  55. */
  56. typedef opt::v::initialized_static_buffer< int, 4 > buffer;
  57. /// Random engine to generate a random position in elimination array
  58. typedef opt::v::c_rand random_engine;
  59. /// Lock type used in elimination, default is cds::sync::spin
  60. typedef cds::sync::spin lock_type;
  61. ///@}
  62. };
  63. /// Metafunction converting option list to \p TreiberStack traits
  64. /**
  65. Supported \p Options are:
  66. - \p opt::allocator - allocator (like \p std::allocator) used for allocating stack nodes. Default is \ref CDS_DEFAULT_ALLOCATOR
  67. - \p opt::back_off - back-off strategy used. If the option is not specified, the \p cds::backoff::Default is used.
  68. - \p opt::memory_model - C++ memory ordering model. Can be \p opt::v::relaxed_ordering (relaxed memory model, the default)
  69. or \p opt::v::sequential_consistent (sequentially consisnent memory model).
  70. - \p opt::item_counter - the type of item counting feature. Default is \p cds::atomicity::empty_item_counter, i.e.
  71. no item counting. Use \p cds::atomicity::item_counter to enable item counting.
  72. - \p opt::stat - the type to gather internal statistics.
  73. Possible option value are: \p treiber_stack::stat, \p treiber_stack::empty_stat (the default),
  74. user-provided class that supports \p %treiber_stack::stat interface.
  75. - \p opt::enable_elimination - enable elimination back-off for the stack. Default value is \p false.
  76. If elimination back-off is enabled, additional options can be specified:
  77. - \p opt::buffer - an initialized buffer type for elimination array, see \p opt::v::initialized_static_buffer, \p opt::v::initialized_dynamic_buffer.
  78. The buffer can be any size: \p Exp2 template parameter of those classes can be \p false.
  79. The size should be selected empirically for your application and hardware, there are no common rules for that.
  80. Default is <tt> %opt::v::initialized_static_buffer< any_type, 4 > </tt>.
  81. - \p opt::random_engine - a random engine to generate a random position in elimination array.
  82. Default is \p opt::v::c_rand.
  83. - \p opt::elimination_backoff - back-off strategy to wait for elimination, default is \p cds::backoff::delay<>
  84. - \p opt::lock_type - a lock type used in elimination back-off, default is \p cds::sync::spin.
  85. Example: declare %TreiberStack with item counting and internal statistics using \p %make_traits
  86. \code
  87. typedef cds::container::TreiberStack< cds::gc::HP, Foo,
  88. typename cds::container::treiber_stack::make_traits<
  89. cds::opt::item_counter< cds::atomicity::item_counter >,
  90. cds::opt::stat< cds::intrusive::treiber_stack::stat<> >
  91. >::type
  92. > myStack;
  93. \endcode
  94. */
  95. template <typename... Options>
  96. struct make_traits {
  97. # ifdef CDS_DOXYGEN_INVOKED
  98. typedef implementation_defined type; ///< Metafunction result
  99. # else
  100. typedef typename cds::opt::make_options<
  101. typename cds::opt::find_type_traits< traits, Options... >::type
  102. , Options...
  103. >::type type;
  104. # endif
  105. };
  106. } // namespace treiber_stack
  107. //@cond
  108. namespace details {
  109. template <typename GC, typename T, typename Traits>
  110. struct make_treiber_stack
  111. {
  112. typedef GC gc;
  113. typedef T value_type;
  114. typedef Traits traits;
  115. struct node_type: public cds::intrusive::treiber_stack::node< gc >
  116. {
  117. value_type m_value;
  118. node_type( const value_type& val )
  119. : m_value( val )
  120. {}
  121. template <typename... Args>
  122. node_type( Args&&... args )
  123. : m_value( std::forward<Args>( args )... )
  124. {}
  125. };
  126. typedef typename std::allocator_traits<typename traits::allocator>::template rebind_alloc< node_type > allocator_type;
  127. typedef cds::details::Allocator< node_type, allocator_type > cxx_allocator;
  128. struct node_deallocator
  129. {
  130. void operator ()( node_type * pNode )
  131. {
  132. cxx_allocator().Delete( pNode );
  133. }
  134. };
  135. struct intrusive_traits: public traits
  136. {
  137. typedef cds::intrusive::treiber_stack::base_hook< cds::opt::gc<gc> > hook;
  138. typedef node_deallocator disposer;
  139. static constexpr const opt::link_check_type link_checker = cds::intrusive::treiber_stack::traits::link_checker;
  140. };
  141. // Result of metafunction
  142. typedef intrusive::TreiberStack< gc, node_type, intrusive_traits > type;
  143. };
  144. } // namespace details
  145. //@endcond
  146. /// Treiber's stack algorithm
  147. /** @ingroup cds_nonintrusive_stack
  148. It is non-intrusive version of Treiber's stack algorithm based on intrusive implementation
  149. intrusive::TreiberStack.
  150. Template arguments:
  151. - \p GC - garbage collector type: \p gc::HP, gc::DHP
  152. - \p T - type stored in the stack.
  153. - \p Traits - stack traits, default is \p treiber_stack::traits. You can use \p treiber_stack::make_traits
  154. metafunction to make your traits or just derive your traits from \p %treiber_stack::traits:
  155. \code
  156. struct myTraits: public cds::container::treiber_stack::traits {
  157. typedef cds::intrusive::treiber_stack::stat<> stat;
  158. typedef cds::atomicity::item_counter item_counter;
  159. };
  160. typedef cds::container::TreiberStack< cds::gc::HP, Foo, myTraits > myStack;
  161. // Equivalent make_traits example:
  162. typedef cds::intrusive::TreiberStack< cds::gc::HP, Foo,
  163. typename cds::intrusive::treiber_stack::make_traits<
  164. cds::opt::item_counter< cds::atomicity::item_counter >,
  165. cds::opt::stat< cds::intrusive::treiber_stack::stat<> >
  166. >::type
  167. > myStack;
  168. \endcode
  169. */
  170. template <
  171. typename GC,
  172. typename T,
  173. typename Traits = treiber_stack::traits
  174. >
  175. class TreiberStack
  176. : public
  177. #ifdef CDS_DOXYGEN_INVOKED
  178. intrusive::TreiberStack< GC, cds::intrusive::treiber_stack::node< T >, Traits >
  179. #else
  180. details::make_treiber_stack< GC, T, Traits >::type
  181. #endif
  182. {
  183. //@cond
  184. typedef details::make_treiber_stack< GC, T, Traits > maker;
  185. typedef typename maker::type base_class;
  186. //@endcond
  187. public:
  188. /// Rebind template arguments
  189. template <typename GC2, typename T2, typename Traits2>
  190. struct rebind {
  191. typedef TreiberStack< GC2, T2, Traits2 > other; ///< Rebinding result
  192. };
  193. public:
  194. typedef T value_type ; ///< Value type stored in the stack
  195. typedef typename base_class::gc gc ; ///< Garbage collector used
  196. typedef typename base_class::back_off back_off ; ///< Back-off strategy used
  197. typedef typename maker::allocator_type allocator_type ; ///< Allocator type used for allocating/deallocating the nodes
  198. typedef typename base_class::memory_model memory_model; ///< Memory ordering. See cds::opt::memory_order option
  199. typedef typename base_class::stat stat ; ///< Internal statistics policy used
  200. protected:
  201. typedef typename maker::node_type node_type ; ///< stack node type (derived from \p intrusive::treiber_stack::node)
  202. //@cond
  203. typedef typename maker::cxx_allocator cxx_allocator;
  204. typedef typename maker::node_deallocator node_deallocator;
  205. //@endcond
  206. protected:
  207. ///@cond
  208. static node_type * alloc_node( const value_type& 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. static void retire_node( node_type * p )
  222. {
  223. gc::template retire<typename base_class::disposer>( p );
  224. }
  225. struct node_disposer {
  226. void operator()( node_type * pNode )
  227. {
  228. free_node( pNode );
  229. }
  230. };
  231. typedef std::unique_ptr< node_type, node_disposer > scoped_node_ptr;
  232. //@endcond
  233. public:
  234. /// Constructs empty stack
  235. TreiberStack()
  236. {}
  237. /// Constructs empty stack and initializes elimination back-off data
  238. /**
  239. This form should be used if you use elimination back-off with dynamically allocated collision array, i.e
  240. \p Options... contains cds::opt::buffer< cds::opt::v::initialized_dynamic_buffer >.
  241. \p nCollisionCapacity parameter specifies the capacity of collision array.
  242. */
  243. TreiberStack( size_t nCollisionCapacity )
  244. : base_class( nCollisionCapacity )
  245. {}
  246. /// \p %TreiberStack is not copy-constructible
  247. TreiberStack( TreiberStack const& ) = delete;
  248. /// Clears the stack on destruction
  249. ~TreiberStack()
  250. {}
  251. /// Pushes copy of \p val on the stack
  252. bool push( value_type const& val )
  253. {
  254. scoped_node_ptr p( alloc_node(val));
  255. if ( base_class::push( *p )) {
  256. p.release();
  257. return true;
  258. }
  259. return false;
  260. }
  261. /// Pushes data of type \ref value_type created from <tt>std::forward<Args>(args)...</tt>
  262. template <typename... Args>
  263. bool emplace( Args&&... args )
  264. {
  265. scoped_node_ptr p( alloc_node_move( std::forward<Args>(args)...));
  266. if ( base_class::push( *p )) {
  267. p.release();
  268. return true;
  269. }
  270. return false;
  271. }
  272. /// Pops an item from the stack
  273. /**
  274. The value of popped item is stored in \p val using assignment operator.
  275. On success functions returns \p true, \p val contains value popped from the stack.
  276. If stack is empty the function returns \p false, \p val is unchanged.
  277. */
  278. bool pop( value_type& val )
  279. {
  280. return pop_with( [&val]( value_type& src ) { val = std::move(src); } );
  281. }
  282. /// Pops an item from the stack with functor
  283. /**
  284. \p Func can be used to copy/move popped item from the stack.
  285. \p Func interface is:
  286. \code
  287. void func( value_type& src );
  288. \endcode
  289. where \p src - item popped.
  290. */
  291. template <typename Func>
  292. bool pop_with( Func f )
  293. {
  294. node_type * p = base_class::pop();
  295. if ( !p )
  296. return false;
  297. f( p->m_value );
  298. retire_node( p );
  299. return true;
  300. }
  301. /// Check if stack is empty
  302. bool empty() const
  303. {
  304. return base_class::empty();
  305. }
  306. /// Clear the stack
  307. void clear()
  308. {
  309. base_class::clear();
  310. }
  311. /// Returns stack's item count
  312. /**
  313. The value returned depends on opt::item_counter option. For atomicity::empty_item_counter,
  314. this function always returns 0.
  315. <b>Warning</b>: even if you use real item counter and it returns 0, this fact is not mean that the stack
  316. is empty. To check emptyness use \ref empty() method.
  317. */
  318. size_t size() const
  319. {
  320. return base_class::size();
  321. }
  322. /// Returns reference to internal statistics
  323. stat const& statistics() const
  324. {
  325. return base_class::statistics();
  326. }
  327. };
  328. }} // namespace cds::container
  329. #endif // #ifndef CDSLIB_CONTAINER_TREIBER_STACK_H