2 // Copyright Oliver Kowalke 2015.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
8 #ifndef BOOST_FIBERS_DETAIL_SPINLOCK_QUEUE_H
9 #define BOOST_FIBERS_DETAIL_SPINLOCK_QUEUE_H
15 #include <boost/config.hpp>
17 #include <boost/fiber/context.hpp>
18 #include <boost/fiber/detail/config.hpp>
19 #include <boost/fiber/detail/spinlock.hpp>
21 #ifdef BOOST_HAS_ABI_HEADERS
22 # include BOOST_ABI_PREFIX
29 class context_spinlock_queue {
31 typedef context * slot_type;
33 alignas(cache_alignment) mutable spinlock splk_{};
34 std::size_t pidx_{ 0 };
35 std::size_t cidx_{ 0 };
36 std::size_t capacity_;
40 slot_type * old_slots = slots_;
41 slots_ = new slot_type[2*capacity_];
42 std::size_t offset = capacity_ - cidx_;
43 std::memcpy( slots_, old_slots + cidx_, offset * sizeof( slot_type) );
45 std::memcpy( slots_ + offset, old_slots, pidx_ * sizeof( slot_type) );
48 pidx_ = capacity_ - 1;
53 bool is_full_() const noexcept {
54 return cidx_ == ((pidx_ + 1) % capacity_);
57 bool is_empty_() const noexcept {
58 return cidx_ == pidx_;
62 context_spinlock_queue( std::size_t capacity = 4096) :
63 capacity_{ capacity } {
64 slots_ = new slot_type[capacity_];
67 ~context_spinlock_queue() {
71 context_spinlock_queue( context_spinlock_queue const&) = delete;
72 context_spinlock_queue & operator=( context_spinlock_queue const&) = delete;
74 bool empty() const noexcept {
75 spinlock_lock lk{ splk_ };
79 void push( context * c) {
80 spinlock_lock lk{ splk_ };
85 pidx_ = (pidx_ + 1) % capacity_;
89 spinlock_lock lk{ splk_ };
90 context * c = nullptr;
91 if ( ! is_empty_() ) {
93 cidx_ = (cidx_ + 1) % capacity_;
99 spinlock_lock lk{ splk_ };
100 context * c = nullptr;
101 if ( ! is_empty_() ) {
103 if ( c->is_context( type::pinned_context) ) {
106 cidx_ = (cidx_ + 1) % capacity_;
114 #ifdef BOOST_HAS_ABI_HEADERS
115 # include BOOST_ABI_SUFFIX
118 #endif // BOOST_FIBERS_DETAIL_SPINLOCK_QUEUE_H