使用 std::deque 或 std::priority_queue 线程安全吗?

2022-01-07 00:00:00 thread-safety deque priority-queue c++ stl

可能的重复:
C++ STL std::set 线程安全吗?
STL 队列的线程安全

我猜不是,我只是想确定一下.意味着 2 个线程使用 相同 std::deque 同时使用 std::deque::push_backpush_front.

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.

同样的问题适用于 std::priority_queue 和函数 std::priority_queue::pushstd::priority_queue::pop..

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 很多.

推荐答案

来自 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

多个阅读器是安全的.多个线程可以同时读取单个容器的内容,这将正常工作.自然,在读取过程中不能有任何写入者对容器进行操作.

Multiple readers are safe. Multiple threads may simultaneously read the contents of a single container, and this will work correctly. Naturally, there must not be any writers acting on the container during the reads.

不同容器的多个写入器是安全的.多个线程可以同时写入不同的容器.

Multiple writers to different containers are safe. Multiple threads may simultaneously write to different containers.

当涉及到线程安全和 STL 容器时,您可以希望有一个允许多个读者的库实现在一个容器上,多个编写器在不同的容器上.您不能指望该库消除手动并发控制的需要,也不能完全依赖任何线程支持.

When it comes to thread safely and STL containers, you can hope for a library implementation that allows multiple readers on one container and multiple writers on separate containers. You can't hope for the library to eliminate the need for manual concurrency control, and you can't rely on any thread support at all.

相关文章