开发者

Is using std::deque or std::priority_queue thread-safe? [duplicate]

开发者 https://www.devze.com 2023-01-23 21:33 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: Is the C++ STL std::set thread-safe?
This question already has answers here: Closed 12 years ago.

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 ti开发者_Go百科me.

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.


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.

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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消