2 * (C) 2017, 2019 Robin Gareus <robin@gareus.org>
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 #ifndef _pbd_mpc_queue_h_
20 #define _pbd_mpc_queue_h_
28 /** Lock free multiple producer, multiple consumer queue
30 * inspired by http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
31 * Kudos to Dmitry Vyukov
34 class /*LIBPBD_API*/ MPMCQueue
37 MPMCQueue (size_t buffer_size = 8)
41 reserve (buffer_size);
50 power_of_two_size (size_t sz)
53 for (power_of_two = 1; 1U << power_of_two < sz; ++power_of_two) ;
54 return 1U << power_of_two;
58 reserve (size_t buffer_size)
60 buffer_size = power_of_two_size (buffer_size);
61 assert ((buffer_size >= 2) && ((buffer_size & (buffer_size - 1)) == 0));
62 if (_buffer_mask >= buffer_size - 1) {
66 _buffer = new cell_t[buffer_size];
67 _buffer_mask = buffer_size - 1;
74 for (size_t i = 0; i <= _buffer_mask; ++i) {
75 g_atomic_int_set (&_buffer[i]._sequence, i);
77 g_atomic_int_set (&_enqueue_pos, 0);
78 g_atomic_int_set (&_dequeue_pos, 0);
82 push_back (T const& data)
85 guint pos = g_atomic_int_get (&_enqueue_pos);
87 cell = &_buffer[pos & _buffer_mask];
88 guint seq = g_atomic_int_get (&cell->_sequence);
89 intptr_t dif = (intptr_t)seq - (intptr_t)pos;
91 if (g_atomic_int_compare_and_exchange (&_enqueue_pos, pos, pos + 1)) {
98 pos = g_atomic_int_get (&_enqueue_pos);
103 g_atomic_int_set (&cell->_sequence, pos + 1);
111 guint pos = g_atomic_int_get (&_dequeue_pos);
113 cell = &_buffer[pos & _buffer_mask];
114 guint seq = g_atomic_int_get (&cell->_sequence);
115 intptr_t dif = (intptr_t)seq - (intptr_t) (pos + 1);
117 if (g_atomic_int_compare_and_exchange (&_dequeue_pos, pos, pos + 1)) {
120 } else if (dif < 0) {
123 pos = g_atomic_int_get (&_dequeue_pos);
128 g_atomic_int_set (&cell->_sequence, pos + _buffer_mask + 1);
134 volatile guint _sequence;
141 volatile guint _enqueue_pos;
142 volatile guint _dequeue_pos;
145 } /* end namespace */