读的时候用共享锁,写的时候用独占锁
struct otherSettingModel
{
inline static const char* jsonFileSavePath = "../data/otherSettingModel.json";
inline static std::shared_timed_mutex fileLocker{};
static otherSettingModel fromFile()
{
std::shared_lock<std::shared_timed_mutex> readLocker(fileLocker);
Q_UNUSED(readLocker)
if(QFile::exists(jsonFileSavePath))
{
QString readJsonFile;
QFile file(jsonFileSavePath);
if (file.open(QIODevice::ReadWrite))
{
readJsonFile = file.readAll();
file.close();
}
otherSettingModel result = Prism::Json::fromJsonString<otherSettingModel>(std::move(readJsonFile));
return result;
}
else
{
saveToFile(otherSettingModel());
return fromFile();
}
}
static void saveToFile(otherSettingModel&& model)
{
std::lock_guard<std::shared_timed_mutex> writeLocker(fileLocker);
Q_UNUSED(writeLocker)
QFile file(jsonFileSavePath);
file.remove();
if (file.open(QIODevice::ReadWrite))
{
QTextStream stream(&file);
stream.setCodec("UTF-8");
stream << Prism::Json::toJsonString(model,true);
}
}
}
标签:std,14,读写,readJsonFile,c++,static,file,otherSettingModel,jsonFileSavePath
From: https://www.cnblogs.com/nocanstillbb/p/17265359.html