Qt: Fix data race and undefined behaviour in games_config

This commit is contained in:
Megamouse 2023-04-26 23:13:28 +02:00
parent cd9ff08235
commit eb5ea82bb1
2 changed files with 17 additions and 1 deletions

View file

@ -19,6 +19,12 @@ games_config::~games_config()
} }
} }
const std::map<std::string, std::string> games_config::get_games() const
{
std::lock_guard lock(m_mutex);
return m_games;
}
std::string games_config::get_path(const std::string& title_id) const std::string games_config::get_path(const std::string& title_id) const
{ {
if (title_id.empty()) if (title_id.empty())
@ -26,6 +32,8 @@ std::string games_config::get_path(const std::string& title_id) const
return {}; return {};
} }
std::lock_guard lock(m_mutex);
if (const auto it = m_games.find(title_id); it != m_games.cend()) if (const auto it = m_games.find(title_id); it != m_games.cend())
{ {
return it->second; return it->second;
@ -36,6 +44,8 @@ std::string games_config::get_path(const std::string& title_id) const
bool games_config::add_game(const std::string& key, const std::string& path) bool games_config::add_game(const std::string& key, const std::string& path)
{ {
std::lock_guard lock(m_mutex);
// Access or create node if does not exist // Access or create node if does not exist
if (auto it = m_games.find(key); it != m_games.end()) if (auto it = m_games.find(key); it != m_games.end())
{ {
@ -64,6 +74,8 @@ bool games_config::add_game(const std::string& key, const std::string& path)
bool games_config::save() bool games_config::save()
{ {
std::lock_guard lock(m_mutex);
YAML::Emitter out; YAML::Emitter out;
out << m_games; out << m_games;
@ -81,6 +93,8 @@ bool games_config::save()
void games_config::load() void games_config::load()
{ {
std::lock_guard lock(m_mutex);
m_games.clear(); m_games.clear();
if (fs::file f{fs::get_config_dir() + "/games.yml", fs::read + fs::create}) if (fs::file f{fs::get_config_dir() + "/games.yml", fs::read + fs::create})

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "Utilities/mutex.h"
#include <map> #include <map>
class games_config class games_config
@ -10,7 +11,7 @@ public:
void set_save_on_dirty(bool enabled) { m_save_on_dirty = enabled; } void set_save_on_dirty(bool enabled) { m_save_on_dirty = enabled; }
const std::map<std::string, std::string>& get_games() const { return m_games; } const std::map<std::string, std::string> get_games() const;
bool is_dirty() const { return m_dirty; } bool is_dirty() const { return m_dirty; }
std::string get_path(const std::string& title_id) const; std::string get_path(const std::string& title_id) const;
@ -22,6 +23,7 @@ private:
void load(); void load();
std::map<std::string, std::string> m_games; std::map<std::string, std::string> m_games;
mutable shared_mutex m_mutex;
bool m_dirty = false; bool m_dirty = false;
bool m_save_on_dirty = true; bool m_save_on_dirty = true;