问题描述
在c ++ 11中,在< functional>
线程中声明的哈希函数类对象是否安全?例如,从多个线程调用此函数是否安全?
In c++11 are the hash function class objects declared in <functional>
thread safe? E.g., is it safe to call this function from multiple threads?
size_t hash1(const std::string& s) {
std::hash<std::string> str_hash;
return str_hash(s);
}
或者,如果有一个全局对象 std: :hash< std :: string> str_hash_global;
,那么从多个线程调用第二个函数是否安全?
or, if one has a global object std::hash<std::string> str_hash_global;
, then is it safe to call this second function from multiple threads?
size_t hash2(const std::string& s) {
return str_hash_global(s);
}
推荐答案
标准库承诺您仅在标准库对象上调用 const
限定的成员函数,则标准库代码不会引起数据争用(参见[res。 on.data.races])。
The standard library promises that if you only call const
-qualified member functions on a standard library object, the standard library code does not cause a data race (cf. [res.on.data.races]).
标准模板 std :: hash
及其所有允许的模板专业化,以及任何满足 Hash
要求([hash.requirements])的用户提供的函子,都必须具有 const 合格的呼叫运营商,因此使用库提供的
std :: hash
专业化不应引起竞争。此外,由于[namespace.std],程序提供的专业化必须满足相同的要求。
The standard template
std::hash
, as well as all its permissible specializations, as well as any user-provided functor that meets the Hash
requirements ([hash.requirements]) must have a const
-qualified call operator due to the requirements, and thus using the library-provided std::hash
specializations should not cause a race. Moreover, due to [namespace.std], program-provided specializations must meet the same requirements.
最后,我想您通常会使用递归地吸引
const
调用:如果多个线程同时在地图中查找值,则它们必须使用地图的 const
Finally, I imagine that you would usually use the race-freeness guarantees by recursively appealing to
const
calls: If you multiple threads concurrently look up values in a map, they have to use the map's const
interface to invoke the above library rule, but then the map only gets to use a constant value of the hasher (or a private copy), and so it can itself only perform race-free hash computations. Whether a racy non-const call operator exists is immeterial at that point.
这篇关于c ++ 11 std :: hash函数对象类的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!