相关疑难解决方法(0)

如何在不使用<mutex>的情况下在C++ 11中实现多线程安全单例

既然C++ 11有多线程,我想知道在不使用互斥锁的情况下实现延迟初始化单例的正确方法是什么(出于性能原因).我想出了这个,但是我并不擅长编写无锁代码,所以我正在寻找更好的解决方案.

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
# include <atomic>
# include <thread>
# include <string>
# include <iostream>
using namespace std;
class Singleton
{

public:
    Singleton()
    {
    }
static  bool isInitialized()
    {
        return (flag==2);
    }
static  bool initizalize(const string& name_)
    {
        if (flag==2)
            return false;// already initialized
        if (flag==1)
            return false;//somebody else is initializing
        if (flag==0)
        {
            int exp=0;
            int desr=1;
            //bool atomic_compare_exchange_strong(std::atomic<T>* obj, T* exp, T desr)
            bool willInitialize=std::atomic_compare_exchange_strong(&flag, &exp, desr); …
Run Code Online (Sandbox Code Playgroud)

c++ singleton multithreading atomic c++11

70
推荐指数
3
解决办法
7万
查看次数

标签 统计

atomic ×1

c++ ×1

c++11 ×1

multithreading ×1

singleton ×1