简体   繁体   中英

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.

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.

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 .

在boost 1.53中有一个锁定队列http://www.boost.org/doc/libs/1_53_0/doc/html/boost/lockfree/queue.html ,没有这样的互斥或smth。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM