From 9247f1bf68198ff99235410e0c0d0fdd1d422ecf Mon Sep 17 00:00:00 2001 From: Reimar Date: Tue, 28 Oct 2025 09:46:50 +0100 Subject: [PATCH] Implement game mutex for thread safety --- src/Game.cpp | 8 +++++++- src/Game.hpp | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Game.cpp b/src/Game.cpp index 27e72ec..4d339cd 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -10,18 +10,24 @@ using namespace std::literals::chrono_literals; void Game::update(std::stop_token stop_token) { while (!stop_token.stop_requested()) { + game_mutex.lock(); + player.update(); renderer.redraw(); map.check_bounds(player.x, player.y); + game_mutex.unlock(); + std::this_thread::sleep_for(16666us); } } -void Game::draw() const +void Game::draw() { + const std::lock_guard lock(game_mutex); + renderer.clear_screen(0x80, 0x40, 0xFF, 0xFF); map.draw(player.x, player.y); diff --git a/src/Game.hpp b/src/Game.hpp index 9da8a4e..1cb70d3 100644 --- a/src/Game.hpp +++ b/src/Game.hpp @@ -14,6 +14,7 @@ private: Map map; std::jthread update_thread; + std::mutex game_mutex; void update(std::stop_token stop_token); @@ -24,7 +25,7 @@ public: void run(); - void draw() const; + void draw(); }; #endif