stack.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. // Copyright (C) 2008-2013 Tim Blechmann
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See
  4. // accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_LOCKFREE_STACK_HPP_INCLUDED
  7. #define BOOST_LOCKFREE_STACK_HPP_INCLUDED
  8. #include <boost/assert.hpp>
  9. #include <boost/checked_delete.hpp>
  10. #include <boost/integer_traits.hpp>
  11. #ifdef BOOST_NO_CXX11_DELETED_FUNCTIONS
  12. #include <boost/noncopyable.hpp>
  13. #endif
  14. #include <boost/static_assert.hpp>
  15. #include <boost/tuple/tuple.hpp>
  16. #include <boost/type_traits/has_trivial_assign.hpp>
  17. #include <boost/type_traits/has_trivial_destructor.hpp>
  18. #include <boost/lockfree/detail/atomic.hpp>
  19. #include <boost/lockfree/detail/copy_payload.hpp>
  20. #include <boost/lockfree/detail/freelist.hpp>
  21. #include <boost/lockfree/detail/parameter.hpp>
  22. #include <boost/lockfree/detail/tagged_ptr.hpp>
  23. namespace boost {
  24. namespace lockfree {
  25. namespace detail {
  26. typedef parameter::parameters<boost::parameter::optional<tag::allocator>,
  27. boost::parameter::optional<tag::capacity>
  28. > stack_signature;
  29. }
  30. /** The stack class provides a multi-writer/multi-reader stack, pushing and popping is lock-free,
  31. * construction/destruction has to be synchronized. It uses a freelist for memory management,
  32. * freed nodes are pushed to the freelist and not returned to the OS before the stack is destroyed.
  33. *
  34. * \b Policies:
  35. *
  36. * - \c boost::lockfree::fixed_sized<>, defaults to \c boost::lockfree::fixed_sized<false> <br>
  37. * Can be used to completely disable dynamic memory allocations during push in order to ensure lockfree behavior.<br>
  38. * If the data structure is configured as fixed-sized, the internal nodes are stored inside an array and they are addressed
  39. * by array indexing. This limits the possible size of the stack to the number of elements that can be addressed by the index
  40. * type (usually 2**16-2), but on platforms that lack double-width compare-and-exchange instructions, this is the best way
  41. * to achieve lock-freedom.
  42. *
  43. * - \c boost::lockfree::capacity<>, optional <br>
  44. * If this template argument is passed to the options, the size of the stack is set at compile-time. <br>
  45. * It this option implies \c fixed_sized<true>
  46. *
  47. * - \c boost::lockfree::allocator<>, defaults to \c boost::lockfree::allocator<std::allocator<void>> <br>
  48. * Specifies the allocator that is used for the internal freelist
  49. *
  50. * \b Requirements:
  51. * - T must have a copy constructor
  52. * */
  53. #ifndef BOOST_DOXYGEN_INVOKED
  54. template <typename T,
  55. class A0 = boost::parameter::void_,
  56. class A1 = boost::parameter::void_,
  57. class A2 = boost::parameter::void_>
  58. #else
  59. template <typename T, ...Options>
  60. #endif
  61. class stack
  62. #ifdef BOOST_NO_CXX11_DELETED_FUNCTIONS
  63. : boost::noncopyable
  64. #endif
  65. {
  66. private:
  67. #ifndef BOOST_DOXYGEN_INVOKED
  68. BOOST_STATIC_ASSERT(boost::has_trivial_assign<T>::value);
  69. BOOST_STATIC_ASSERT(boost::has_trivial_destructor<T>::value);
  70. typedef typename detail::stack_signature::bind<A0, A1, A2>::type bound_args;
  71. static const bool has_capacity = detail::extract_capacity<bound_args>::has_capacity;
  72. static const size_t capacity = detail::extract_capacity<bound_args>::capacity;
  73. static const bool fixed_sized = detail::extract_fixed_sized<bound_args>::value;
  74. static const bool node_based = !(has_capacity || fixed_sized);
  75. static const bool compile_time_sized = has_capacity;
  76. struct node
  77. {
  78. node(T const & val):
  79. v(val)
  80. {}
  81. typedef typename detail::select_tagged_handle<node, node_based>::handle_type handle_t;
  82. handle_t next;
  83. const T v;
  84. };
  85. typedef typename detail::extract_allocator<bound_args, node>::type node_allocator;
  86. typedef typename detail::select_freelist<node, node_allocator, compile_time_sized, fixed_sized, capacity>::type pool_t;
  87. typedef typename pool_t::tagged_node_handle tagged_node_handle;
  88. // check compile-time capacity
  89. BOOST_STATIC_ASSERT((mpl::if_c<has_capacity,
  90. mpl::bool_<capacity - 1 < boost::integer_traits<boost::uint16_t>::const_max>,
  91. mpl::true_
  92. >::type::value));
  93. struct implementation_defined
  94. {
  95. typedef node_allocator allocator;
  96. typedef std::size_t size_type;
  97. };
  98. #endif
  99. #ifndef BOOST_NO_CXX11_DELETED_FUNCTIONS
  100. stack(stack const &) = delete;
  101. stack(stack &&) = delete;
  102. const stack& operator=( const stack& ) = delete;
  103. #endif
  104. public:
  105. typedef T value_type;
  106. typedef typename implementation_defined::allocator allocator;
  107. typedef typename implementation_defined::size_type size_type;
  108. /**
  109. * \return true, if implementation is lock-free.
  110. *
  111. * \warning It only checks, if the top stack node and the freelist can be modified in a lock-free manner.
  112. * On most platforms, the whole implementation is lock-free, if this is true. Using c++0x-style atomics,
  113. * there is no possibility to provide a completely accurate implementation, because one would need to test
  114. * every internal node, which is impossible if further nodes will be allocated from the operating system.
  115. *
  116. * */
  117. bool is_lock_free (void) const
  118. {
  119. return tos.is_lock_free() && pool.is_lock_free();
  120. }
  121. //! Construct stack
  122. // @{
  123. stack(void):
  124. pool(node_allocator(), capacity)
  125. {
  126. BOOST_ASSERT(has_capacity);
  127. initialize();
  128. }
  129. template <typename U>
  130. explicit stack(typename node_allocator::template rebind<U>::other const & alloc):
  131. pool(alloc, capacity)
  132. {
  133. BOOST_STATIC_ASSERT(has_capacity);
  134. initialize();
  135. }
  136. explicit stack(allocator const & alloc):
  137. pool(alloc, capacity)
  138. {
  139. BOOST_ASSERT(has_capacity);
  140. initialize();
  141. }
  142. // @}
  143. //! Construct stack, allocate n nodes for the freelist.
  144. // @{
  145. explicit stack(size_type n):
  146. pool(node_allocator(), n)
  147. {
  148. BOOST_ASSERT(!has_capacity);
  149. initialize();
  150. }
  151. template <typename U>
  152. stack(size_type n, typename node_allocator::template rebind<U>::other const & alloc):
  153. pool(alloc, n)
  154. {
  155. BOOST_STATIC_ASSERT(!has_capacity);
  156. initialize();
  157. }
  158. // @}
  159. /** Allocate n nodes for freelist
  160. *
  161. * \pre only valid if no capacity<> argument given
  162. * \note thread-safe, may block if memory allocator blocks
  163. *
  164. * */
  165. void reserve(size_type n)
  166. {
  167. BOOST_STATIC_ASSERT(!has_capacity);
  168. pool.template reserve<true>(n);
  169. }
  170. /** Allocate n nodes for freelist
  171. *
  172. * \pre only valid if no capacity<> argument given
  173. * \note not thread-safe, may block if memory allocator blocks
  174. *
  175. * */
  176. void reserve_unsafe(size_type n)
  177. {
  178. BOOST_STATIC_ASSERT(!has_capacity);
  179. pool.template reserve<false>(n);
  180. }
  181. /** Destroys stack, free all nodes from freelist.
  182. *
  183. * \note not thread-safe
  184. *
  185. * */
  186. ~stack(void)
  187. {
  188. T dummy;
  189. while(unsynchronized_pop(dummy))
  190. {}
  191. }
  192. private:
  193. #ifndef BOOST_DOXYGEN_INVOKED
  194. void initialize(void)
  195. {
  196. tos.store(tagged_node_handle(pool.null_handle(), 0));
  197. }
  198. void link_nodes_atomic(node * new_top_node, node * end_node)
  199. {
  200. tagged_node_handle old_tos = tos.load(detail::memory_order_relaxed);
  201. for (;;) {
  202. tagged_node_handle new_tos (pool.get_handle(new_top_node), old_tos.get_tag());
  203. end_node->next = pool.get_handle(old_tos);
  204. if (tos.compare_exchange_weak(old_tos, new_tos))
  205. break;
  206. }
  207. }
  208. void link_nodes_unsafe(node * new_top_node, node * end_node)
  209. {
  210. tagged_node_handle old_tos = tos.load(detail::memory_order_relaxed);
  211. tagged_node_handle new_tos (pool.get_handle(new_top_node), old_tos.get_tag());
  212. end_node->next = pool.get_pointer(old_tos);
  213. tos.store(new_tos, memory_order_relaxed);
  214. }
  215. template <bool Threadsafe, bool Bounded, typename ConstIterator>
  216. tuple<node*, node*> prepare_node_list(ConstIterator begin, ConstIterator end, ConstIterator & ret)
  217. {
  218. ConstIterator it = begin;
  219. node * end_node = pool.template construct<Threadsafe, Bounded>(*it++);
  220. if (end_node == NULL) {
  221. ret = begin;
  222. return make_tuple<node*, node*>(NULL, NULL);
  223. }
  224. node * new_top_node = end_node;
  225. end_node->next = NULL;
  226. try {
  227. /* link nodes */
  228. for (; it != end; ++it) {
  229. node * newnode = pool.template construct<Threadsafe, Bounded>(*it);
  230. if (newnode == NULL)
  231. break;
  232. newnode->next = new_top_node;
  233. new_top_node = newnode;
  234. }
  235. } catch (...) {
  236. for (node * current_node = new_top_node; current_node != NULL;) {
  237. node * next = current_node->next;
  238. pool.template destruct<Threadsafe>(current_node);
  239. current_node = next;
  240. }
  241. throw;
  242. }
  243. ret = it;
  244. return make_tuple(new_top_node, end_node);
  245. }
  246. #endif
  247. public:
  248. /** Pushes object t to the stack.
  249. *
  250. * \post object will be pushed to the stack, if internal node can be allocated
  251. * \returns true, if the push operation is successful.
  252. *
  253. * \note Thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
  254. * from the OS. This may not be lock-free.
  255. * \throws if memory allocator throws
  256. * */
  257. bool push(T const & v)
  258. {
  259. return do_push<false>(v);
  260. }
  261. /** Pushes object t to the stack.
  262. *
  263. * \post object will be pushed to the stack, if internal node can be allocated
  264. * \returns true, if the push operation is successful.
  265. *
  266. * \note Thread-safe and non-blocking. If internal memory pool is exhausted, the push operation will fail
  267. * */
  268. bool bounded_push(T const & v)
  269. {
  270. return do_push<true>(v);
  271. }
  272. #ifndef BOOST_DOXYGEN_INVOKED
  273. private:
  274. template <bool Bounded>
  275. bool do_push(T const & v)
  276. {
  277. node * newnode = pool.template construct<true, Bounded>(v);
  278. if (newnode == 0)
  279. return false;
  280. link_nodes_atomic(newnode, newnode);
  281. return true;
  282. }
  283. template <bool Bounded, typename ConstIterator>
  284. ConstIterator do_push(ConstIterator begin, ConstIterator end)
  285. {
  286. node * new_top_node;
  287. node * end_node;
  288. ConstIterator ret;
  289. tie(new_top_node, end_node) = prepare_node_list<true, Bounded>(begin, end, ret);
  290. if (new_top_node)
  291. link_nodes_atomic(new_top_node, end_node);
  292. return ret;
  293. }
  294. public:
  295. #endif
  296. /** Pushes as many objects from the range [begin, end) as freelist node can be allocated.
  297. *
  298. * \return iterator to the first element, which has not been pushed
  299. *
  300. * \note Operation is applied atomically
  301. * \note Thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
  302. * from the OS. This may not be lock-free.
  303. * \throws if memory allocator throws
  304. */
  305. template <typename ConstIterator>
  306. ConstIterator push(ConstIterator begin, ConstIterator end)
  307. {
  308. return do_push<false, ConstIterator>(begin, end);
  309. }
  310. /** Pushes as many objects from the range [begin, end) as freelist node can be allocated.
  311. *
  312. * \return iterator to the first element, which has not been pushed
  313. *
  314. * \note Operation is applied atomically
  315. * \note Thread-safe and non-blocking. If internal memory pool is exhausted, the push operation will fail
  316. * \throws if memory allocator throws
  317. */
  318. template <typename ConstIterator>
  319. ConstIterator bounded_push(ConstIterator begin, ConstIterator end)
  320. {
  321. return do_push<true, ConstIterator>(begin, end);
  322. }
  323. /** Pushes object t to the stack.
  324. *
  325. * \post object will be pushed to the stack, if internal node can be allocated
  326. * \returns true, if the push operation is successful.
  327. *
  328. * \note Not thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
  329. * from the OS. This may not be lock-free.
  330. * \throws if memory allocator throws
  331. * */
  332. bool unsynchronized_push(T const & v)
  333. {
  334. node * newnode = pool.template construct<false, false>(v);
  335. if (newnode == 0)
  336. return false;
  337. link_nodes_unsafe(newnode, newnode);
  338. return true;
  339. }
  340. /** Pushes as many objects from the range [begin, end) as freelist node can be allocated.
  341. *
  342. * \return iterator to the first element, which has not been pushed
  343. *
  344. * \note Not thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
  345. * from the OS. This may not be lock-free.
  346. * \throws if memory allocator throws
  347. */
  348. template <typename ConstIterator>
  349. ConstIterator unsynchronized_push(ConstIterator begin, ConstIterator end)
  350. {
  351. node * new_top_node;
  352. node * end_node;
  353. ConstIterator ret;
  354. tie(new_top_node, end_node) = prepare_node_list<false, false>(begin, end, ret);
  355. if (new_top_node)
  356. link_nodes_unsafe(new_top_node, end_node);
  357. return ret;
  358. }
  359. /** Pops object from stack.
  360. *
  361. * \post if pop operation is successful, object will be copied to ret.
  362. * \returns true, if the pop operation is successful, false if stack was empty.
  363. *
  364. * \note Thread-safe and non-blocking
  365. *
  366. * */
  367. bool pop(T & ret)
  368. {
  369. return pop<T>(ret);
  370. }
  371. /** Pops object from stack.
  372. *
  373. * \pre type T must be convertible to U
  374. * \post if pop operation is successful, object will be copied to ret.
  375. * \returns true, if the pop operation is successful, false if stack was empty.
  376. *
  377. * \note Thread-safe and non-blocking
  378. *
  379. * */
  380. template <typename U>
  381. bool pop(U & ret)
  382. {
  383. BOOST_STATIC_ASSERT((boost::is_convertible<T, U>::value));
  384. detail::consume_via_copy<U> consumer(ret);
  385. return consume_one(consumer);
  386. }
  387. /** Pops object from stack.
  388. *
  389. * \post if pop operation is successful, object will be copied to ret.
  390. * \returns true, if the pop operation is successful, false if stack was empty.
  391. *
  392. * \note Not thread-safe, but non-blocking
  393. *
  394. * */
  395. bool unsynchronized_pop(T & ret)
  396. {
  397. return unsynchronized_pop<T>(ret);
  398. }
  399. /** Pops object from stack.
  400. *
  401. * \pre type T must be convertible to U
  402. * \post if pop operation is successful, object will be copied to ret.
  403. * \returns true, if the pop operation is successful, false if stack was empty.
  404. *
  405. * \note Not thread-safe, but non-blocking
  406. *
  407. * */
  408. template <typename U>
  409. bool unsynchronized_pop(U & ret)
  410. {
  411. BOOST_STATIC_ASSERT((boost::is_convertible<T, U>::value));
  412. tagged_node_handle old_tos = tos.load(detail::memory_order_relaxed);
  413. node * old_tos_pointer = pool.get_pointer(old_tos);
  414. if (!pool.get_pointer(old_tos))
  415. return false;
  416. node * new_tos_ptr = pool.get_pointer(old_tos_pointer->next);
  417. tagged_node_handle new_tos(pool.get_handle(new_tos_ptr), old_tos.get_next_tag());
  418. tos.store(new_tos, memory_order_relaxed);
  419. detail::copy_payload(old_tos_pointer->v, ret);
  420. pool.template destruct<false>(old_tos);
  421. return true;
  422. }
  423. /** consumes one element via a functor
  424. *
  425. * pops one element from the stack and applies the functor on this object
  426. *
  427. * \returns true, if one element was consumed
  428. *
  429. * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
  430. * */
  431. template <typename Functor>
  432. bool consume_one(Functor & f)
  433. {
  434. tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
  435. for (;;) {
  436. node * old_tos_pointer = pool.get_pointer(old_tos);
  437. if (!old_tos_pointer)
  438. return false;
  439. tagged_node_handle new_tos(old_tos_pointer->next, old_tos.get_next_tag());
  440. if (tos.compare_exchange_weak(old_tos, new_tos)) {
  441. f(old_tos_pointer->v);
  442. pool.template destruct<true>(old_tos);
  443. return true;
  444. }
  445. }
  446. }
  447. /// \copydoc boost::lockfree::stack::consume_one(Functor & rhs)
  448. template <typename Functor>
  449. bool consume_one(Functor const & f)
  450. {
  451. tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
  452. for (;;) {
  453. node * old_tos_pointer = pool.get_pointer(old_tos);
  454. if (!old_tos_pointer)
  455. return false;
  456. tagged_node_handle new_tos(old_tos_pointer->next, old_tos.get_next_tag());
  457. if (tos.compare_exchange_weak(old_tos, new_tos)) {
  458. f(old_tos_pointer->v);
  459. pool.template destruct<true>(old_tos);
  460. return true;
  461. }
  462. }
  463. }
  464. /** consumes all elements via a functor
  465. *
  466. * sequentially pops all elements from the stack and applies the functor on each object
  467. *
  468. * \returns number of elements that are consumed
  469. *
  470. * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
  471. * */
  472. template <typename Functor>
  473. size_t consume_all(Functor & f)
  474. {
  475. size_t element_count = 0;
  476. while (consume_one(f))
  477. element_count += 1;
  478. return element_count;
  479. }
  480. /// \copydoc boost::lockfree::stack::consume_all(Functor & rhs)
  481. template <typename Functor>
  482. size_t consume_all(Functor const & f)
  483. {
  484. size_t element_count = 0;
  485. while (consume_one(f))
  486. element_count += 1;
  487. return element_count;
  488. }
  489. /**
  490. * \return true, if stack is empty.
  491. *
  492. * \note It only guarantees that at some point during the execution of the function the stack has been empty.
  493. * It is rarely practical to use this value in program logic, because the stack can be modified by other threads.
  494. * */
  495. bool empty(void) const
  496. {
  497. return pool.get_pointer(tos.load()) == NULL;
  498. }
  499. private:
  500. #ifndef BOOST_DOXYGEN_INVOKED
  501. detail::atomic<tagged_node_handle> tos;
  502. static const int padding_size = BOOST_LOCKFREE_CACHELINE_BYTES - sizeof(tagged_node_handle);
  503. char padding[padding_size];
  504. pool_t pool;
  505. #endif
  506. };
  507. } /* namespace lockfree */
  508. } /* namespace boost */
  509. #endif /* BOOST_LOCKFREE_STACK_HPP_INCLUDED */