假设我有以下代码:
#include<concurrent_unordered_map.h>
struct firstStruct {
<irrelevant code>
}
struct secondStruct {
void func(){
<CRITICAL CODE>
}
}
假设我有这个:
concurrent_unordered_map<firstStruct,secondStruct> cmap = ...
我们假设 cmap
已填充,并且 firstStruct f
和secondStruct 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/