C++ std::set 线程安全吗?

2022-01-07 00:00:00 c++ stl std stdset

我有一个关于 std::set 线程安全的问题.

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.

但请考虑以下场景:

  • 线程'A'遍历一组shared_ptr
  • 线程B"偶尔会向该集合中添加项目.

我在程序运行时遇到了段错误,但我不确定为什么会发生这种情况.缺乏线程安全是原因吗?

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

推荐答案

STL 没有内置线程支持,所以你必须扩展 STL使用您自己的同步机制编写代码以在其中使用 STL多线程环境.

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.

例如看这里:link文字

由于set是一个容器类,MSDN有以下关于容器线程安全的说法.

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

单个对象对于从多个线程读取是线程安全的.例如,给定一个对象 A,同时从线程 1 和线程 2 读取 A 是安全的.

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.

如果一个线程正在写入单个对象,则必须保护在同一线程或其他线程上对该对象的所有读取和写入.例如,给定一个对象 A,如果线程 1 正在写入 A,则必须阻止线程 2 读取或写入 A.

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.

即使另一个线程正在读取或写入同一类型的不同实例,读取和写入一个类型的一个实例也是安全的.例如,给定相同类型的对象 A 和 B,如果 A 在线程 1 中写入而 B 在线程 2 中读取则是安全的.

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.

相关文章