c++14 读写锁

读的时候用共享锁,写的时候用独占锁

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);
        }

    }

}
posted @ 2023-03-28 15:29  马肯尼煤牙巴骨  阅读(115)  评论(0)    收藏  举报