I\'ve spent today looking into lockless queues. I have a multiple producer, multiple consumer situation. I implemented, for testing, a system using the Interlocked SList t
I think there's some interesting discussion on this topic here, particularly this thread.
viraptor solution is locking , there are no multiple producer/multiple consumer lockless queue algotihms im aware of .
You could probably implement a limited-size queue with least difficulty... I was thinking about it lately and came up with this design, but you can probably find many other interesting ideas: (WARNING: it might have some issues!)
head
== tail
, there are no itemsenqueue(ptr)
, Interlocked-Swap tail
with NULL (prev_tail
is the swapped value)
prev_tail == NULL
, try againprev_tail + 1
(with wraparound) == head
, your queue is fullptr
in *prev_tail
and assign prev_tail+1
to tail
(watch out for buffer wrap-around)dequeue()
make a copy tmp_head=head and check tmp_head == tail
*tmp_head
as ptr
head
with tmp_head
swap head
with head+1
ptr
You can wait on both head and tail CAS operations, but if the queue is not contended, you should succeed the first time, without unnecessary locks.
Unlimited-size queues are "a bit" harder ;) But you should be able to create a big-enough queue for most needs.
These guys have, maybe you could find some inspiration there. The other interesting files are yqueue.hpp and atomic_ptr.hpp
You might want to take a look at Herb Sutters implementation of a low lock queue.
http://www.drdobbs.com/hpc-high-performance-computing/211601363
It does use the c++0x atomics but it would be (should be) easy to implement with your specific architectures atomic ops (__sync_* using GNU, atomic_* on solaris etc).