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