std :: map thread-safety [英] std::map thread-safety

查看:237
本文介绍了std :: map thread-safety的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在std :: map中对象的引用是线程安全的吗?

Is reference to object in std::map is thread safe?

std::map< std::string, Object >   _objects;

映射可以从许多线程改变,并且这个访问是同步的,但是引用值(Object& )只能从1个实例和线程访问。是使用对象&是安全的,如果另一个线程将添加项目映射?它会重新分配吗?

map can be changed from many threads and this access is synchronized, but reference to value (Object &) accessable just from 1 instance and thread. is write operations with Object & is safe if another thread will add items to map? will it reallocate?

推荐答案

C ++ 11标准保证 const 方法访问容器是安全的从不同的线程(即,使用 const 方法)。

The C++11 standard guarantees that const method access to containers is safe from different threads (ie, both use const methods).

[container.requirements.dataraces]状态

In addition, [container.requirements.dataraces] states


实施时需要避免数据竞争,当
的内容包含的对象在不同除了向量< bool>

换句话说,除了向量< bool> 修改不同的内容不是数据竞争。

In other words, except for vector<bool> modifying distinct contents is not a data race.

如果一个线程使另一个线程使用的迭代器失效,这显然是一个数据竞争(并导致未定义的行为)。如果一个线程对一个容器进行非 - const 访问,而另一个线程执行 const 访问,和未定义的行为)。 (注意:为了多线程的目的,一些函数被考虑 const ,包括 begin end 和其他函数(和方法)非 - const ,因为它们返回非 - const 迭代器。 [] 包含在这个伪 - const 除了 map unordered_set 等 - 23.2.2.1)。

Now, if one thread invalidates an iterator used by another thread, clearly this is a data race (and results in undefined behavior). If one thread does non-const access to a container, and another does const access, that is a data race (and undefined behavior). (Note: a number of functions are "considered const" for the purpose of multithreading, including begin, end and other functions (and methods) that are non-const simply because they return non-const iterators. [] is included in this set of pseudo-const for thread safety reasons, except for map and unordered_set etc -- 23.2.2.1).

然而,看起来如果你有一个对容器中的元素的引用,并参与不会使该引用在另一个线程中失效的操作,并且永远不会写入另一个线程中的该元素,那么你可以安全地读取该引用。类似地,如果其他线程从未从元素中读取,则写入该元素不会导致未定义的行为。

However, it appears that if you have a reference to an element within the container, and engage in operations that do not invalidate that reference in another thread, and never write to that element in another thread, you can safely read from that reference. Similarly, if other threads never even read from the element, then writing to that element shouldn't result in undefined behavior.

对于标准引用,17.6.5.9.5似乎以保证标准库中的函数不会消失,并且不必要地读写元素。

For standards references, 17.6.5.9.5 seems to guarantee that functions from the standard library won't run away and read/write elements needlessly.

所以简短的答案:你是安全的,只要另一个线程不会直接与映射中的特定条目混淆。

So the short answer: you are safe, so long as the other thread doesn't directly mess with that particular entry in the map.

这篇关于std :: map thread-safety的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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