Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-blocking thread-safe queue in C++?

Is there a thread-safe, non-blocking queue class in the C++?

Probably a basic question but I haven't been doing C++ for a long time...

EDIT: removed STL requirement.

like image 550
jldupont Avatar asked Oct 29 '09 17:10

jldupont


People also ask

What is non blocking queue?

Unlike a LinkedBlockingQueue, a ConcurrentLinkedQueue is a non-blocking queue. Thus, it does not block a thread once the queue is empty. Instead, it returns null. Since its unbounded, it'll throw a java.

How do I make a queue thread safe?

Thread safe means that you have to isolate any shared data. Here your shared data is the pointer to the queue.So , in general , any time you have operations on the queue you need to protect queue and prevent multiple threads reach your queue at the same time. One good way is to implement Condition Variables.

What are thread safe queues?

The C++ thread safe queue allows to use the queue by multiple thread in multi-threaded code. The thread safe queue is not a built-in method or class in C++; it can be implemented with the help of built-in STL libraries.


2 Answers

Assuming your CPU has a double-pointer-wide compare-and-swap (compxchg8b on 486 or higher, compxchg16b on most amd64 machines [not present on some early models by Intel])... There is an algorithm here.

Update: It's not hard to translate this to C++ if you aren't afraid of doing a bit of work. :P

This algorithm assumes a "pointer with tag" structure which looks like this:

// Be aware that copying this structure has to be done atomically...  template <class T> struct pointer {    T *ptr;    uintptr_t tag; }; 

Then you want to wrap the instructions lock cmpxchg{8|16}b with some inline asm...

Maybe then you can write the queue node like this:

template <class T> struct queue_node {     T value;     pointer<queue_node<T> > next; }; 

The rest is more or less a transcription of the algorithm I linked to...

like image 194
asveikau Avatar answered Oct 12 '22 04:10

asveikau


Since the current C++ standard doesn't even acknowledge the existence of threads, there is most certainly nothing thread-safe in the STL or any other part of the standard library.

like image 29
sbi Avatar answered Oct 12 '22 05:10

sbi