相关疑难解决方法(0)

Meyers对Singleton模式线程的实现是否安全?

以下实现,使用延迟初始化Singleton(Meyers'Seingleton)线程安全吗?

static Singleton& instance()
{
     static Singleton s;
     return s;
}
Run Code Online (Sandbox Code Playgroud)

如果没有,为什么以及如何使其线程安全?

c++ multithreading design-patterns

129
推荐指数
5
解决办法
5万
查看次数

std::call_once 是阻塞调用吗?

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)

c++ multithreading std c++11

5
推荐指数
1
解决办法
2031
查看次数

标签 统计

c++ ×2

multithreading ×2

c++11 ×1

design-patterns ×1

std ×1