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

萝らか妹 提交于 2019-12-19 05:15:30

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/21302142/is-stdqueue-thread-safe-with-producer-and-multiple-consumers

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