更新
如果我们查看草案 C++ 标准部分30.4.4.1
Struct once_flag我们可以看到构造函数定义为:
constexpr once_flag() noexcept;
因为它是一个constexpr ,所以您的静态实例将被静态初始化,我们可以在30.4.4.2
Function call_once部分中看到一个使用静态实例的示例:
void g() {
static std::once_flag flag2;
std::call_once(flag2, initializer());
}
原来的
如果我们查看std::once_flag的文档,它会说:
once_flag();
Cnstructs an once_flag object. The internal state is set to indicate that no function
has been called yet.
如果我们进一步查看call_once的文档文档,我们会看到以下示例,该示例演示了如何使用std::once_flag
:
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
void do_once()
{
std::call_once(flag, [](){ std::cout << "Called once" << std::endl; });
}
int main()
{
std::thread t1(do_once);
std::thread t2(do_once);
std::thread t3(do_once);
std::thread t4(do_once);
t1.join();
t2.join();
t3.join();
t4.join();
}
具有以下预期输出:
Called once