C++ 对生产者和多个消费者来说是 std::queue 线程安全的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21302142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
is std::queue thread safe with producer and multiple consumers
提问by unikat
how can I make a queue thread safe? I need to push / pop / front / back and clear. is there something similar in boost?
如何使队列线程安全?我需要推/弹出/前/后并清除。boost中有类似的东西吗?
I have one producer and one or more consumer.
我有一个生产者和一个或多个消费者。
采纳答案by mindo
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).
您必须保护对std::queue
. 如果您正在使用 boost 保护它使用boost::mutex
. 现在,如果您有多个读者和一个作者线程,请查看boost::shared_lock
(对于读者)和boost::unique_lock
(对于作者)。
However if you will encounter writer thread starvation look at boost::shared_mutex
.
但是,如果您会遇到作家线程饥饿,请查看boost::shared_mutex
.
回答by juanchopanza
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.
std::queue
如果一个或多个线程正在写入,则不是线程安全的。并且它的接口不利于线程安全的实现,因为它具有单独的方法,例如pop()
,size()
并且empty()
必须在外部进行同步。
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.
* 搜索“并发队列 C++”应该会产生很多结果。我在这里实现了一个非常简单的玩具,其中的限制是只能使用标准的 C++。另请参阅 Anthony Williams 的书C++ concurrency in action以及他的博客。
回答by Mike Minaev
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.
在 boost 1.53 中有一个 lockfee 队列http://www.boost.org/doc/libs/1_53_0/doc/html/boost/lockfree/queue.html,没有像这样的互斥锁或 smth。
回答by MSalters
You have to protect it, e.g. with a std::mutex
, on everyoperation. Boost would be an alternative if you don't have C++11 yet.
您必须std::mutex
在每次操作时保护它,例如使用, 。如果您还没有 C++11,Boost 将是一个替代方案。