Pergunta

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.

Foi útil?

Solução 2

You must protect access to std::queue. If you are using boost protect it using boost::mutex. Now if you have multiple readers and one writer thread look at boost::shared_lock (for readers) and boost::unique_lock(for writer).

However if you will encounter writer thread starvation look at boost::shared_mutex.

Outras dicas

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.

in boost 1.53 there is a lockfee queue http://www.boost.org/doc/libs/1_53_0/doc/html/boost/lockfree/queue.html, no mutex or smth like this.

You have to protect it, e.g. with a std::mutex, on every operation. Boost would be an alternative if you don't have C++11 yet.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top