c++ - 线程安全单例类——我这样做对吗?

标签 c++ multithreading c++11 singleton

我正在创建一个系统状态类,它需要在读/写时是线程安全的。我正在使用单例设计模式来实现它。 我基于这些 Stackoverflow 问题的指针:

  1. Singleton: How it Should be Used
  2. C++ Singleton Design Pattern

这是我的代码的一个浓缩示例。本质上,它只是我需要跟踪并在多个线程之间共享的一些状态变量。我知道事实上只需要一个状态实例,而且我知道它需要线程安全且恒定。此实现会确保这一点吗?

// System_State.h
class System_State
{
public:
    static System_State &getInstance()
    {
        static System_State stateInstance;
        return stateInstance;
    }

    System_State(System_State const&)   = delete;
    void operator=(System_State const&) = delete;

    // Example Setter with mutex guard
    void setWifiConnectedStatus(uint8_t _status)
    {
        std::lock_guard<std::mutex> lock(mtx);
        Wifi.ConnectedStatus = _status;
    }

private:
    System_State() 
    {
        initializeState();
    }

    void initializeState();

    std::mutex mtx;

    static struct WifiService
    {
        uint8_t     ConnectedStatus;
        std::string CurrentConnection;
        std::string SavedNetworks;
        std::string AvailableNetworks;
        std::string ForgetNetwork;
        std::string ConnectTo;
        std::string DisconnectFrom;
    } Wifi;

    static struct ScanService
    {
        std::string PerformScan;
        std::string ScanStatus;
        uint8_t     ScanProgress;
    } Scan;

    static struct UploadDataService
    {
        std::string PerformUpload;
        uint8_t     UploadProgress;
        uint8_t     ItemsWaitingToBeUploaded;
    } UploadData;

    static std::string LEDControlBrightness;
    static uint8_t     BatteryPercentage;
};

这里是一些主要的例子

//main.cpp
#include <thread>

void loop1()
{
    System_State state = System_State::getInstance();
    while(true)
    {
        //do randomness with state
    }
}

void loop2()
{
    System_State state2 = System_State::getInstance();
    while(true)
    {
        //do randomness with state2
    }
}

int main()
{
    std::thread t1(loop1);
    std::thread t2(loop2);
    // do and join and all that!
    return 0;
}

最佳答案

你的不是惯用的单例,因为它仍然容易出现所谓的“静态初始化顺序失败”。

惯用的单例没有静态类成员,相反它的实例函数看起来像

static MySingleton& instance() {
    static MySingleton the_ton;
    return the_ton;
}

有关惨败的更多信息:static initialization order fiasco

关于c++ - 线程安全单例类——我这样做对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54987308/

相关文章:

java - 在 java 8 中将核心池大小设置为 0 的有效用例是什么?

C++11 可重入类锁定策略

c++ - 是否有标准的 C++11 解决方案来转义单引号?

c++ - 是否可以为 boost::random::uniform_int_distribution<> 设置确定性种子?

c++ - 在 MFC 应用程序中监听 UDP 或切换到 TCP

c++ - C++ 中的函数重载按值或按引用传递参数

c++ - CMake 安装到/bin

java - 对于阻塞集合中的每个

c++ - 如何使用 OpenMP 以线程安全的方式生成随机数

c++ - 在不转换对象的情况下调用子类方法