Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is std::queue thread safe with producer and multiple consumers

how can I make a queue thread safe? I need to push / pop / front / back and clear. is there something similar in boost?

I have one producer and one or more consumer.

like image 745
unikat Avatar asked Jan 23 '14 07:01

unikat


People also ask

Is C++ std :: queue thread safe?

Modern C++: Writing a thread-safe Queue The STL provides a high-performance queue class in std::queue<T> ; however, the API is not very intuitive, or easy, to use and it is not safe to access from multiple threads.

Is a queue thread safe?

The Queue module provides a FIFO implementation suitable for multi-threaded programming. It can be used to pass messages or other data between producer and consumer threads safely.

Is std :: list size () thread safe?

No, they're not thread-safe.

Is std :: map thread safe?

It isn't thread safe, insert from two threads and you can end up in an inconstant state.


1 Answers

std::queue is not thread safe if one or more threads are writing. And its interface is not conducive to a thread safe implementation, because it has separate methods such as pop(), size() and empty() which would have to be synchronized externally.

A common approach* is to implement a queue type with a simpler interface, and use locking mechanisms internally to provide synchronization.

* A search for "concurrent queue C++" should yield many results. I implemented a very simple toy one here, where the limitation was to use only standard C++. See also Anthony Williams' book C++ concurrency in action, as well as his blog.

like image 101
juanchopanza Avatar answered Sep 24 '22 13:09

juanchopanza