std :: map中的线程安全 [英] thread safety in std::map

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

问题描述

在多线程环境中使用无锁的std映射是否安全?保证两个线程永远不会操纵映射中的相同条目.

Is it safe to use std map without a lock in multi-thread environment? Where It is guaranteed that two threads never be manipulating the same entry in the map.

已经存在一个问题,但是我对多个线程正在访问映射中的不同条目的情况特别感兴趣.尤其是无序的地图.

There is already a question on this but I am particularly interested in the case where multiple threads are accessing different entries in the map. particularly unordered maps.

推荐答案

只要没有线程在修改映射,它是安全的.如果线程正在修改映射的不同元素也是安全的(前提是元素本身不会通过例如修改某些全局状态而引起竞争条件):

It is safe as long as none of the threads are modifying the map. It is also safe if threads are modifying different elements of the map (provided the elements themselves don't cause race conditions by, for example, modifying some global state):

17.6.5.9避免数据争用中,标准库保证对容器的并发 const 访问是安全的(至少在容器运行的范围内.)允许通过 const 访问进行变异,可能在元素级别发生数据争夺.)

In 17.6.5.9 Data race avoidance, the standard library guarantees that concurrent const access to containers is safe (at least as far s the containers go. If the elements allow mutation via const access there could be data races at the element level.)

23.2.2容器数据竞争中进一步保证:如果对容器 elements 进行修改/读取,则非const并发访问是安全的> 1 .

In 23.2.2 Container data races further guarantees are made: non-const concurrent access is safe if the modifications/reads are to different elements of the container1.

一旦有一个线程对容器或容器中的同一元素进行了修改,而其他线程则进行了读取或写入,则您会面临竞争条件和不确定的行为.

As soon as you have one thread making modifications to the container or to the same element in the container while others read or write, you are open to race conditions and undefined behaviour.

1,除了 std :: vector< bool>

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

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