Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
987 views
in Technique[技术] by (71.8m points)

stl - Is the C++ std::set thread-safe?

I've a question about the thread safety of std::set.

As far as I know I can iterate over a set and add/erase members and that doesn't invalidate the iterators.

But consider following scenario:

  • thread 'A' iterates over a set of shared_ptr<Type>
  • thread 'B' occasionally adds items to this set.

I've experienced segfaults as the program runs and I'm not sure why this happens. Is lack of thread safety the cause?

question from:https://stackoverflow.com/questions/1362110/is-the-c-stdset-thread-safe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

STL has no built in thread support, so you'll have to extend the STL code with your own synchronization mechanisms to use STL in a multithreaded environment.

For example look here: link text

Since set is a container class MSDN has following to say about the thread safety of the containers.

A single object is thread safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously.

If a single object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected. For example, given an object A, if thread 1 is writing to A, then thread 2 must be prevented from reading from or writing to A.

It is safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given objects A and B of the same type, it is safe if A is being written in thread 1 and B is being read in thread 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...