1 // Copyright (C) 2008-2013 Tim Blechmann
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)
7 #ifndef BOOST_LOCKFREE_STACK_HPP_INCLUDED
8 #define BOOST_LOCKFREE_STACK_HPP_INCLUDED
10 #include <boost/assert.hpp>
11 #include <boost/checked_delete.hpp>
12 #include <boost/core/allocator_access.hpp>
13 #include <boost/core/no_exceptions_support.hpp>
14 #include <boost/integer_traits.hpp>
15 #include <boost/static_assert.hpp>
16 #include <boost/tuple/tuple.hpp>
17 #include <boost/type_traits/is_copy_constructible.hpp>
19 #include <boost/lockfree/detail/atomic.hpp>
20 #include <boost/lockfree/detail/copy_payload.hpp>
21 #include <boost/lockfree/detail/freelist.hpp>
22 #include <boost/lockfree/detail/parameter.hpp>
23 #include <boost/lockfree/detail/tagged_ptr.hpp>
25 #include <boost/lockfree/lockfree_forward.hpp>
27 #ifdef BOOST_HAS_PRAGMA_ONCE
35 typedef parameter::parameters<boost::parameter::optional<tag::allocator>,
36 boost::parameter::optional<tag::capacity>
41 /** The stack class provides a multi-writer/multi-reader stack, pushing and popping is lock-free,
42 * construction/destruction has to be synchronized. It uses a freelist for memory management,
43 * freed nodes are pushed to the freelist and not returned to the OS before the stack is destroyed.
47 * - \c boost::lockfree::fixed_sized<>, defaults to \c boost::lockfree::fixed_sized<false> <br>
48 * Can be used to completely disable dynamic memory allocations during push in order to ensure lockfree behavior.<br>
49 * If the data structure is configured as fixed-sized, the internal nodes are stored inside an array and they are addressed
50 * by array indexing. This limits the possible size of the stack to the number of elements that can be addressed by the index
51 * type (usually 2**16-2), but on platforms that lack double-width compare-and-exchange instructions, this is the best way
52 * to achieve lock-freedom.
54 * - \c boost::lockfree::capacity<>, optional <br>
55 * If this template argument is passed to the options, the size of the stack is set at compile-time. <br>
56 * It this option implies \c fixed_sized<true>
58 * - \c boost::lockfree::allocator<>, defaults to \c boost::lockfree::allocator<std::allocator<void>> <br>
59 * Specifies the allocator that is used for the internal freelist
62 * - T must have a copy constructor
64 #ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
65 template <typename T, class A0, class A1, class A2>
67 template <typename T, typename ...Options>
72 #ifndef BOOST_DOXYGEN_INVOKED
73 BOOST_STATIC_ASSERT(boost::is_copy_constructible<T>::value);
75 #ifdef BOOST_NO_CXX11_VARIADIC_TEMPLATES
76 typedef typename detail::stack_signature::bind<A0, A1, A2>::type bound_args;
78 typedef typename detail::stack_signature::bind<Options...>::type bound_args;
81 static const bool has_capacity = detail::extract_capacity<bound_args>::has_capacity;
82 static const size_t capacity = detail::extract_capacity<bound_args>::capacity;
83 static const bool fixed_sized = detail::extract_fixed_sized<bound_args>::value;
84 static const bool node_based = !(has_capacity || fixed_sized);
85 static const bool compile_time_sized = has_capacity;
93 typedef typename detail::select_tagged_handle<node, node_based>::handle_type handle_t;
98 typedef typename detail::extract_allocator<bound_args, node>::type node_allocator;
99 typedef typename detail::select_freelist<node, node_allocator, compile_time_sized, fixed_sized, capacity>::type pool_t;
100 typedef typename pool_t::tagged_node_handle tagged_node_handle;
102 // check compile-time capacity
103 BOOST_STATIC_ASSERT((mpl::if_c<has_capacity,
104 mpl::bool_<capacity - 1 < boost::integer_traits<boost::uint16_t>::const_max>,
108 struct implementation_defined
110 typedef node_allocator allocator;
111 typedef std::size_t size_type;
116 BOOST_DELETED_FUNCTION(stack(stack const&))
117 BOOST_DELETED_FUNCTION(stack& operator= (stack const&))
120 typedef T value_type;
121 typedef typename implementation_defined::allocator allocator;
122 typedef typename implementation_defined::size_type size_type;
125 * \return true, if implementation is lock-free.
127 * \warning It only checks, if the top stack node and the freelist can be modified in a lock-free manner.
128 * On most platforms, the whole implementation is lock-free, if this is true. Using c++0x-style atomics,
129 * there is no possibility to provide a completely accurate implementation, because one would need to test
130 * every internal node, which is impossible if further nodes will be allocated from the operating system.
133 bool is_lock_free (void) const
135 return tos.is_lock_free() && pool.is_lock_free();
138 /** Construct a fixed-sized stack
140 * \pre Must specify a capacity<> argument
143 pool(node_allocator(), capacity)
145 // Don't use BOOST_STATIC_ASSERT() here since it will be evaluated when compiling
146 // this function and this function may be compiled even when it isn't being used.
147 BOOST_ASSERT(has_capacity);
151 /** Construct a fixed-sized stack with a custom allocator
153 * \pre Must specify a capacity<> argument
155 template <typename U>
156 explicit stack(typename boost::allocator_rebind<node_allocator, U>::type const & alloc):
157 pool(alloc, capacity)
159 BOOST_STATIC_ASSERT(has_capacity);
163 /** Construct a fixed-sized stack with a custom allocator
165 * \pre Must specify a capacity<> argument
167 explicit stack(allocator const & alloc):
168 pool(alloc, capacity)
170 // Don't use BOOST_STATIC_ASSERT() here since it will be evaluated when compiling
171 // this function and this function may be compiled even when it isn't being used.
172 BOOST_ASSERT(has_capacity);
176 /** Construct a variable-sized stack
178 * Allocate n nodes initially for the freelist
180 * \pre Must \b not specify a capacity<> argument
182 explicit stack(size_type n):
183 pool(node_allocator(), n)
185 // Don't use BOOST_STATIC_ASSERT() here since it will be evaluated when compiling
186 // this function and this function may be compiled even when it isn't being used.
187 BOOST_ASSERT(!has_capacity);
191 /** Construct a variable-sized stack with a custom allocator
193 * Allocate n nodes initially for the freelist
195 * \pre Must \b not specify a capacity<> argument
197 template <typename U>
198 stack(size_type n, typename boost::allocator_rebind<node_allocator, U>::type const & alloc):
201 BOOST_STATIC_ASSERT(!has_capacity);
205 /** Allocate n nodes for freelist
207 * \pre only valid if no capacity<> argument given
208 * \note thread-safe, may block if memory allocator blocks
211 void reserve(size_type n)
213 // Don't use BOOST_STATIC_ASSERT() here since it will be evaluated when compiling
214 // this function and this function may be compiled even when it isn't being used.
215 BOOST_ASSERT(!has_capacity);
216 pool.template reserve<true>(n);
219 /** Allocate n nodes for freelist
221 * \pre only valid if no capacity<> argument given
222 * \note not thread-safe, may block if memory allocator blocks
225 void reserve_unsafe(size_type n)
227 // Don't use BOOST_STATIC_ASSERT() here since it will be evaluated when compiling
228 // this function and this function may be compiled even when it isn't being used.
229 BOOST_ASSERT(!has_capacity);
230 pool.template reserve<false>(n);
233 /** Destroys stack, free all nodes from freelist.
235 * \note not thread-safe
240 detail::consume_noop consume_functor;
241 (void)consume_all(consume_functor);
245 #ifndef BOOST_DOXYGEN_INVOKED
246 void initialize(void)
248 tos.store(tagged_node_handle(pool.null_handle(), 0));
251 void link_nodes_atomic(node * new_top_node, node * end_node)
253 tagged_node_handle old_tos = tos.load(detail::memory_order_relaxed);
255 tagged_node_handle new_tos (pool.get_handle(new_top_node), old_tos.get_tag());
256 end_node->next = pool.get_handle(old_tos);
258 if (tos.compare_exchange_weak(old_tos, new_tos))
263 void link_nodes_unsafe(node * new_top_node, node * end_node)
265 tagged_node_handle old_tos = tos.load(detail::memory_order_relaxed);
267 tagged_node_handle new_tos (pool.get_handle(new_top_node), old_tos.get_tag());
268 end_node->next = pool.get_handle(old_tos);
270 tos.store(new_tos, memory_order_relaxed);
273 template <bool Threadsafe, bool Bounded, typename ConstIterator>
274 tuple<node*, node*> prepare_node_list(ConstIterator begin, ConstIterator end, ConstIterator & ret)
276 ConstIterator it = begin;
277 node * end_node = pool.template construct<Threadsafe, Bounded>(*it++);
278 if (end_node == NULL) {
280 return make_tuple<node*, node*>(NULL, NULL);
283 node * new_top_node = end_node;
284 end_node->next = NULL;
288 for (; it != end; ++it) {
289 node * newnode = pool.template construct<Threadsafe, Bounded>(*it);
292 newnode->next = new_top_node;
293 new_top_node = newnode;
295 } BOOST_CATCH (...) {
296 for (node * current_node = new_top_node; current_node != NULL;) {
297 node * next = current_node->next;
298 pool.template destruct<Threadsafe>(current_node);
306 return make_tuple(new_top_node, end_node);
311 /** Pushes object t to the stack.
313 * \post object will be pushed to the stack, if internal node can be allocated
314 * \returns true, if the push operation is successful.
316 * \note Thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
317 * from the OS. This may not be lock-free.
318 * \throws if memory allocator throws
320 bool push(T const & v)
322 return do_push<false>(v);
325 /** Pushes object t to the stack.
327 * \post object will be pushed to the stack, if internal node can be allocated
328 * \returns true, if the push operation is successful.
330 * \note Thread-safe and non-blocking. If internal memory pool is exhausted, the push operation will fail
332 bool bounded_push(T const & v)
334 return do_push<true>(v);
337 #ifndef BOOST_DOXYGEN_INVOKED
339 template <bool Bounded>
340 bool do_push(T const & v)
342 node * newnode = pool.template construct<true, Bounded>(v);
346 link_nodes_atomic(newnode, newnode);
350 template <bool Bounded, typename ConstIterator>
351 ConstIterator do_push(ConstIterator begin, ConstIterator end)
357 tie(new_top_node, end_node) = prepare_node_list<true, Bounded>(begin, end, ret);
359 link_nodes_atomic(new_top_node, end_node);
367 /** Pushes as many objects from the range [begin, end) as freelist node can be allocated.
369 * \return iterator to the first element, which has not been pushed
371 * \note Operation is applied atomically
372 * \note Thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
373 * from the OS. This may not be lock-free.
374 * \throws if memory allocator throws
376 template <typename ConstIterator>
377 ConstIterator push(ConstIterator begin, ConstIterator end)
379 return do_push<false, ConstIterator>(begin, end);
382 /** Pushes as many objects from the range [begin, end) as freelist node can be allocated.
384 * \return iterator to the first element, which has not been pushed
386 * \note Operation is applied atomically
387 * \note Thread-safe and non-blocking. If internal memory pool is exhausted, the push operation will fail
388 * \throws if memory allocator throws
390 template <typename ConstIterator>
391 ConstIterator bounded_push(ConstIterator begin, ConstIterator end)
393 return do_push<true, ConstIterator>(begin, end);
397 /** Pushes object t to the stack.
399 * \post object will be pushed to the stack, if internal node can be allocated
400 * \returns true, if the push operation is successful.
402 * \note Not thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
403 * from the OS. This may not be lock-free.
404 * \throws if memory allocator throws
406 bool unsynchronized_push(T const & v)
408 node * newnode = pool.template construct<false, false>(v);
412 link_nodes_unsafe(newnode, newnode);
416 /** Pushes as many objects from the range [begin, end) as freelist node can be allocated.
418 * \return iterator to the first element, which has not been pushed
420 * \note Not thread-safe. If internal memory pool is exhausted and the memory pool is not fixed-sized, a new node will be allocated
421 * from the OS. This may not be lock-free.
422 * \throws if memory allocator throws
424 template <typename ConstIterator>
425 ConstIterator unsynchronized_push(ConstIterator begin, ConstIterator end)
431 tie(new_top_node, end_node) = prepare_node_list<false, false>(begin, end, ret);
433 link_nodes_unsafe(new_top_node, end_node);
439 /** Pops object from stack.
441 * \post if pop operation is successful, object will be copied to ret.
442 * \returns true, if the pop operation is successful, false if stack was empty.
444 * \note Thread-safe and non-blocking
452 /** Pops object from stack.
454 * \pre type T must be convertible to U
455 * \post if pop operation is successful, object will be copied to ret.
456 * \returns true, if the pop operation is successful, false if stack was empty.
458 * \note Thread-safe and non-blocking
461 template <typename U>
464 BOOST_STATIC_ASSERT((boost::is_convertible<T, U>::value));
465 detail::consume_via_copy<U> consumer(ret);
467 return consume_one(consumer);
471 /** Pops object from stack.
473 * \post if pop operation is successful, object will be copied to ret.
474 * \returns true, if the pop operation is successful, false if stack was empty.
476 * \note Not thread-safe, but non-blocking
479 bool unsynchronized_pop(T & ret)
481 return unsynchronized_pop<T>(ret);
484 /** Pops object from stack.
486 * \pre type T must be convertible to U
487 * \post if pop operation is successful, object will be copied to ret.
488 * \returns true, if the pop operation is successful, false if stack was empty.
490 * \note Not thread-safe, but non-blocking
493 template <typename U>
494 bool unsynchronized_pop(U & ret)
496 BOOST_STATIC_ASSERT((boost::is_convertible<T, U>::value));
497 tagged_node_handle old_tos = tos.load(detail::memory_order_relaxed);
498 node * old_tos_pointer = pool.get_pointer(old_tos);
500 if (!pool.get_pointer(old_tos))
503 node * new_tos_ptr = pool.get_pointer(old_tos_pointer->next);
504 tagged_node_handle new_tos(pool.get_handle(new_tos_ptr), old_tos.get_next_tag());
506 tos.store(new_tos, memory_order_relaxed);
507 detail::copy_payload(old_tos_pointer->v, ret);
508 pool.template destruct<false>(old_tos);
512 /** consumes one element via a functor
514 * pops one element from the stack and applies the functor on this object
516 * \returns true, if one element was consumed
518 * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
520 template <typename Functor>
521 bool consume_one(Functor & f)
523 tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
526 node * old_tos_pointer = pool.get_pointer(old_tos);
527 if (!old_tos_pointer)
530 tagged_node_handle new_tos(old_tos_pointer->next, old_tos.get_next_tag());
532 if (tos.compare_exchange_weak(old_tos, new_tos)) {
533 f(old_tos_pointer->v);
534 pool.template destruct<true>(old_tos);
540 /// \copydoc boost::lockfree::stack::consume_one(Functor & rhs)
541 template <typename Functor>
542 bool consume_one(Functor const & f)
544 tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
547 node * old_tos_pointer = pool.get_pointer(old_tos);
548 if (!old_tos_pointer)
551 tagged_node_handle new_tos(old_tos_pointer->next, old_tos.get_next_tag());
553 if (tos.compare_exchange_weak(old_tos, new_tos)) {
554 f(old_tos_pointer->v);
555 pool.template destruct<true>(old_tos);
561 /** consumes all elements via a functor
563 * sequentially pops all elements from the stack and applies the functor on each object
565 * \returns number of elements that are consumed
567 * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
569 template <typename Functor>
570 size_t consume_all(Functor & f)
572 size_t element_count = 0;
573 while (consume_one(f))
576 return element_count;
579 /// \copydoc boost::lockfree::stack::consume_all(Functor & rhs)
580 template <typename Functor>
581 size_t consume_all(Functor const & f)
583 size_t element_count = 0;
584 while (consume_one(f))
587 return element_count;
590 /** consumes all elements via a functor
592 * atomically pops all elements from the stack and applies the functor on each object
594 * \returns number of elements that are consumed
596 * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
598 template <typename Functor>
599 size_t consume_all_atomic(Functor & f)
601 size_t element_count = 0;
602 tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
605 node * old_tos_pointer = pool.get_pointer(old_tos);
606 if (!old_tos_pointer)
609 tagged_node_handle new_tos(pool.null_handle(), old_tos.get_next_tag());
611 if (tos.compare_exchange_weak(old_tos, new_tos))
615 tagged_node_handle nodes_to_consume = old_tos;
618 node * node_pointer = pool.get_pointer(nodes_to_consume);
622 node * next_node = pool.get_pointer(node_pointer->next);
625 pool.template destruct<true>(nodes_to_consume);
629 tagged_node_handle next(pool.get_handle(next_node), nodes_to_consume.get_next_tag());
630 pool.template destruct<true>(nodes_to_consume);
631 nodes_to_consume = next;
634 return element_count;
637 /// \copydoc boost::lockfree::stack::consume_all_atomic(Functor & rhs)
638 template <typename Functor>
639 size_t consume_all_atomic(Functor const & f)
641 size_t element_count = 0;
642 tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
645 node * old_tos_pointer = pool.get_pointer(old_tos);
646 if (!old_tos_pointer)
649 tagged_node_handle new_tos(pool.null_handle(), old_tos.get_next_tag());
651 if (tos.compare_exchange_weak(old_tos, new_tos))
655 tagged_node_handle nodes_to_consume = old_tos;
658 node * node_pointer = pool.get_pointer(nodes_to_consume);
662 node * next_node = pool.get_pointer(node_pointer->next);
665 pool.template destruct<true>(nodes_to_consume);
669 tagged_node_handle next(pool.get_handle(next_node), nodes_to_consume.get_next_tag());
670 pool.template destruct<true>(nodes_to_consume);
671 nodes_to_consume = next;
674 return element_count;
677 /** consumes all elements via a functor
679 * atomically pops all elements from the stack and applies the functor on each object in reversed order
681 * \returns number of elements that are consumed
683 * \note Thread-safe and non-blocking, if functor is thread-safe and non-blocking
685 template <typename Functor>
686 size_t consume_all_atomic_reversed(Functor & f)
688 size_t element_count = 0;
689 tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
692 node * old_tos_pointer = pool.get_pointer(old_tos);
693 if (!old_tos_pointer)
696 tagged_node_handle new_tos(pool.null_handle(), old_tos.get_next_tag());
698 if (tos.compare_exchange_weak(old_tos, new_tos))
702 tagged_node_handle nodes_to_consume = old_tos;
704 node * last_node_pointer = NULL;
705 tagged_node_handle nodes_in_reversed_order;
707 node * node_pointer = pool.get_pointer(nodes_to_consume);
708 node * next_node = pool.get_pointer(node_pointer->next);
710 node_pointer->next = pool.get_handle(last_node_pointer);
711 last_node_pointer = node_pointer;
714 nodes_in_reversed_order = nodes_to_consume;
718 tagged_node_handle next(pool.get_handle(next_node), nodes_to_consume.get_next_tag());
719 nodes_to_consume = next;
723 node * node_pointer = pool.get_pointer(nodes_in_reversed_order);
727 node * next_node = pool.get_pointer(node_pointer->next);
730 pool.template destruct<true>(nodes_in_reversed_order);
734 tagged_node_handle next(pool.get_handle(next_node), nodes_in_reversed_order.get_next_tag());
735 pool.template destruct<true>(nodes_in_reversed_order);
736 nodes_in_reversed_order = next;
739 return element_count;
742 /// \copydoc boost::lockfree::stack::consume_all_atomic_reversed(Functor & rhs)
743 template <typename Functor>
744 size_t consume_all_atomic_reversed(Functor const & f)
746 size_t element_count = 0;
747 tagged_node_handle old_tos = tos.load(detail::memory_order_consume);
750 node * old_tos_pointer = pool.get_pointer(old_tos);
751 if (!old_tos_pointer)
754 tagged_node_handle new_tos(pool.null_handle(), old_tos.get_next_tag());
756 if (tos.compare_exchange_weak(old_tos, new_tos))
760 tagged_node_handle nodes_to_consume = old_tos;
762 node * last_node_pointer = NULL;
763 tagged_node_handle nodes_in_reversed_order;
765 node * node_pointer = pool.get_pointer(nodes_to_consume);
766 node * next_node = pool.get_pointer(node_pointer->next);
768 node_pointer->next = pool.get_handle(last_node_pointer);
769 last_node_pointer = node_pointer;
772 nodes_in_reversed_order = nodes_to_consume;
776 tagged_node_handle next(pool.get_handle(next_node), nodes_to_consume.get_next_tag());
777 nodes_to_consume = next;
781 node * node_pointer = pool.get_pointer(nodes_in_reversed_order);
785 node * next_node = pool.get_pointer(node_pointer->next);
788 pool.template destruct<true>(nodes_in_reversed_order);
792 tagged_node_handle next(pool.get_handle(next_node), nodes_in_reversed_order.get_next_tag());
793 pool.template destruct<true>(nodes_in_reversed_order);
794 nodes_in_reversed_order = next;
797 return element_count;
800 * \return true, if stack is empty.
802 * \note It only guarantees that at some point during the execution of the function the stack has been empty.
803 * It is rarely practical to use this value in program logic, because the stack can be modified by other threads.
805 bool empty(void) const
807 return pool.get_pointer(tos.load()) == NULL;
811 #ifndef BOOST_DOXYGEN_INVOKED
812 detail::atomic<tagged_node_handle> tos;
814 static const int padding_size = BOOST_LOCKFREE_CACHELINE_BYTES - sizeof(tagged_node_handle);
815 char padding[padding_size];
821 } /* namespace lockfree */
822 } /* namespace boost */
824 #endif /* BOOST_LOCKFREE_STACK_HPP_INCLUDED */