c++ - 并发无序映射查找线程调用的函数是否安全?

标签 c++ multithreading visual-studio concurrency thread-safety

假设我有以下代码:

#include<concurrent_unordered_map.h>

struct firstStruct {
<irrelevant code>
}
struct secondStruct {
    void func(){ 
       <CRITICAL CODE>
    }
}

假设我有这个:

concurrent_unordered_map<firstStruct,secondStruct> cmap = ...

我们假设 cmap已填充,并且 firstStruct fsecondStruct s(key,value)(f,s)存在于cmap中。

如果我使用以下代码片段

cmap[f].func();

是否执行 <CRITICAL CODE>func()来自secondStruct s线程安全吗?

此外,如果我有以下代码片段,并且可能在不同线程中同时执行,会发生什么情况?

cmap[f].func();

SecondStruct s2 = ... ;
cmap[f] = s2;

如果(key,value)(f,s)更改为(f,s2)由一个线程执行,如果另一个线程碰巧正在执行<CRITICAL CODE>,会发生什么情况? ?

最佳答案

来自proposal对于 concurrent_unordered_map

For serialized execution, the operations behave the same as their current STL counterparts. The only change is allowance for concurrency. Executing any of the following operations concurrently on a concurrent unordered container does not introduce a data race:

get_allocator
empty, size, max_size
begin, end, cbegin, cend
insert
find, count, equal_range, operator[], at
load_factor
max_load_factor() 
operator==, operator!= 

assuming that the requisite operations on the key type (and mapped_type if applicable) are concurrency safe.

强调我的

所以,operartor[]是线程安全的,但您对其返回值执行的操作也必须是线程安全的,以保证不会发生数据争用。这意味着<CRITICAL CODE>func()本身必须是线程安全的。如果不是,那么类似

cmap[f].func();
SecondStruct s2 = ... ;
cmap[f] = s2;

也不是线程安全的,因为当您将新对象分配给键时该函数仍在运行。

关于c++ - 并发无序映射查找线程调用的函数是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52317585/

相关文章:

java - 如何在 JVM 被杀死之前让线程永远存活?

c++ - 多线程事件检查器不打印任何东西

visual-studio - Visual Studio中有没有选择当前行的快捷方式?

c++ - qt打开一个带有不支持警告图像格式的jpg文件

multithreading - 从单个应用程序中的多个线程调用 dll 函数是否安全?

c++ - vector vector 的初始化?

c# - Git 从存储库中删除 *.sln.docstates

visual-studio - Visual Studio 2015 无法为 Cordova 项目创建发布版本

c++ - 如何使用 C/C++ 获取原始相机数据?

c++ - 用于显示位图和处理按钮按下的简单框架