是C ++ std :: set线程安全吗? [英] Is the C++ std::set thread-safe?

查看:1306
本文介绍了是C ++ std :: set线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于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< Type>

  • 线程'B'偶尔向该集合添加项目。

我在程序运行时遇到了segfaults,我不知道为什么会发生这种情况。缺少线程安全的原因?

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
代码与您自己的同步机制在
a多线程环境中使用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.

例如看看这里:链接文字

由于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读取或向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.

这篇关于是C ++ std :: set线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆