如果我有一个像这样的全球价值获取者
bool get_global_bool() {
static const bool b{get_the_value()};
return b;
}
我知道
b
将以线程安全的方式初始化,但我是否也能保证同时调用 get_global_bool
的多个线程永远不会多次执行 get_the_value
?
是的,根据cppref
If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once).
Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison.
好吧,您还可以通过检查 gen asm 输出来验证它,输出将类似于 x86-64 gcc trunk 上的以下内容
get_the_value():
movzx eax, BYTE PTR v[rip]
ret
get_global_bool():
movzx eax, BYTE PTR guard variable for get_global_bool()::b[rip]
test al, al
je .L14
movzx eax, BYTE PTR get_global_bool()::b[rip]
ret
.L14:
sub rsp, 8
mov edi, OFFSET FLAT:guard variable for get_global_bool()::b
call __cxa_guard_acquire
test eax, eax
jne .L15
movzx eax, BYTE PTR get_global_bool()::b[rip]
add rsp, 8
ret
.L15:
movzx eax, BYTE PTR v[rip]
mov edi, OFFSET FLAT:guard variable for get_global_bool()::b
mov BYTE PTR get_global_bool()::b[rip], al
call __cxa_guard_release
movzx eax, BYTE PTR get_global_bool()::b[rip]
add rsp, 8
ret
您可以看到 get_the_value 受 cxa_guard 保护并且仅调用一次