以下实现,使用延迟初始化Singleton(Meyers'Seingleton)线程安全吗?
static Singleton& instance()
{
static Singleton s;
return s;
}
Run Code Online (Sandbox Code Playgroud)
如果没有,为什么以及如何使其线程安全?
我std::call_once在代码中仅使用一次来初始化一些共享变量。调用代码位于由多个线程触发的回调内。我有兴趣知道,因为我在文档中找不到它,所以std::call_once本质上是否是阻塞的,就好像有一个std::lock_guard相反?实际情况看起来确实如此。
例如,以下内容将在调用"Done"之前打印:print()
#include <future>
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
void print()
{
for(int i=0;i<10;i++)
{
std::cout << "Hi, my name is " << std::this_thread::get_id()
<< ", what?" << std::endl;
}
}
void do_once()
{
std::cout << "sleeping for a while..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "Done" << std::endl;
}
void work()
{
std::call_once(flag, [](){ do_once(); });
print();
}
int main()
{
auto handle1 = std::async(std::launch::async, work);
auto handle2 …Run Code Online (Sandbox Code Playgroud)