使用 std::deque 或 std::priority_queue 是线程安全的吗?
我猜不是,我只是想确保。 意味着 2 个线程同时使用 相同 std::deque 使用 std::deque::push_back
或 push_front
。
同样的问题也适用于 std::priority_queue
以及函数 std::priority_queue::push
和 std::priority_queue::pop
..那些容器是线程安全的?或者我应该亲自将其编程为线程安全的?
Tnx很多。
Possible Duplicates:
Is the C++ STL std::set thread-safe?
Thread safety for STL queue
I'm guessing it isn't, I just want to make sure.
meaning 2 threads using the same std::deque using std::deque::push_back
or push_front
at the same time.
Same question goes for std::priority_queue
and the functions std::priority_queue::push
and std::priority_queue::pop
..
Are those containers thread-safe? Or I should personally program it to be thread-safe?
Tnx a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 Scott Myer 的《Effective STL Item 12》。对 STL 容器的线程安全性抱有现实的期望
From Scott Myer's Effective STL Item 12. Have realistic expectations about the thread safety of STL containers
STL 不提供任何线程安全保证。从多个线程修改同一容器时尤其如此。
您正在使用的 STL 实现可能会提供一定程度的线程安全性,但您需要查看实现的文档。
The STL does not provide any guarantees for thread safety. This is especially the case when modifying the same container from multiple threads.
The implementation of the STL that you're using may provide some level of thread safety, but you would need to look at the documentation for your implementation.
当您说它们线程安全时,大概您的意思是您可以在多个线程中使用它们而不必锁定任何内容。
理论上,你可能有 2 个线程,一个推到后面,一个推到前面,你可能会逃脱它,尽管我会很谨慎,因为实现者不能保证随着迭代器变得线程安全在任一端插入都无效,如果push_back的实现使用“end”并且push_front的实现使用“begin”,那么这将在另一个线程的调用中无效,并且可能会在你身上爆炸。
std::priority_queue 几乎肯定不能在两个线程中一起使用,大概对于生产者/消费者线程来说,一个推入一个弹出,您需要先锁定。
我发现当我基于 std::deque 编写生产者/消费者队列时,我允许生产者一次推送多个项目,并且允许消费者扫描整个队列进行处理。这意味着每次批量插入只需一次锁定,因此减少了需要锁定的次数。
When you say are they thread safe, presumably you mean can you use them in multiple threads without having to lock anything.
In theory you could potentially have 2 threads, one pushing to the back and one to the front, and you'd probably get away with it although I would be wary because the implementor is not under a guarantee to make it thread safe as iterators become invalidated with inserts at either end, if the implementation of push_back used "end" and of push_front used "begin", such would be invalidated in the call by the other thread, and might blow up on you.
std::priority_queue is almost certainly not usable in two threads together, presumably for producer/consumer threads, with one pushing and one popping and you will need to lock first.
I found that when I wrote a producer/consumer queue based around std::deque, I allowed the producer also to push more than one item at a time, and the consumer to sweep the entire queue to process. This meant only one lock per bulk-insert, so reduced the number of times you needed to lock.