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

依然范特西╮ 提交于 2019-12-18 11:10:55

问题


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.


回答1:


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...




回答2:


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.




回答3:


This seems to have been a popular subject on Dr. Dobb's last year:

  • Lock-Free Queues
  • Writing Lock-Free Code: A Corrected Queue



回答4:


You need to implement it yourself or use a library implementing it. To do it yourself, you may want to have a look at this:

Implementing a Thread-Safe Queue using Condition Variables




回答5:


Short answer - no. STL does not concern itself with concurrency (at least on the specification level.) Current C++ standard says nothing about threads.

You can easily build such a queue on top of STL and Boost though - just wrap std::queue and boost::mutex in your custom class.




回答6:


STL containers are not thread-safe, you should implement your treatment for concurrent access.
There is this project (C++) that aims to serve concurrent accesses : CPH STL
and paper about.




回答7:


May be too late now. For future reference, this one is a good implementation of lock-free queues (built in thread safety with some caveats).

Multi producer - Multi consumer

http://moodycamel.com/blog/2014/a-fast-general-purpose-lock-free-queue-for-c++

https://github.com/cameron314/concurrentqueue

Single producer - Single consumer

http://moodycamel.com/blog/2013/a-fast-lock-free-queue-for-c++

https://github.com/cameron314/readerwriterqueue




回答8:


The currently unofficial Boost.Lockfree is something to consider. I use both the FIFO and the atomic types.



来源:https://stackoverflow.com/questions/1645326/non-blocking-thread-safe-queue-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!