我有以下类:C++ 11 const - 我的代码是否线程安全?
class Object
{
public:
Object() {}
const std::string& get_name() const
{
if(_name.empty()) {
std::lock_guard<std::mutex> lock(_lock);
// Check if its still empty. Some other thread might have gotten here first
if(_name.empty()) {
//Run expensive operation
_name = get_object_name();
}
}
return _name;
}
private:
std::string get_object_name(); // <- Expensive function
mutable std::mutex _lock;
mutable std::string _name;
};
由于对get_object_name
是一个昂贵的功能的事实,我愿做一个排序延迟初始化的并且只调用它的第一次get_name()
被调用。如果它从未被调用,那么我不会浪费资源来获取名称。
我很担心第一次致电_name.empty()
。我的当前代码是否保证是线程安全的,还是需要将锁移动到函数的顶部?
我看了一些香草萨特的会谈,特别是this one,在这张幻灯片上出现:
http://i.imgur.com/Jz4luYe.png
导致我相信,到empty()
调用是线程安全的。但我的变量(_name
)是mutable
。这个“const ==线程安全”规则是否仍然适用于此?
get_name()
是唯一可以修改_name
的功能。
有该模式的名称:双检锁(https://en.wikipedia.org/维基/双checked_locking)。它适用于某些环境,而不适用于其他环境。当它不起作用时,原因很微妙。 –