gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:23:13 25 4
gpt4 key购买 nike

我正在创建一个系统状态类,它需要在读/写时是线程安全的。我正在使用单例设计模式来实现它。我基于这些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com