Implement game mutex for thread safety

This commit is contained in:
Reimar 2025-10-28 09:46:50 +01:00
parent d2476fa5df
commit 9247f1bf68
2 changed files with 9 additions and 2 deletions

View File

@ -10,18 +10,24 @@ using namespace std::literals::chrono_literals;
void Game::update(std::stop_token stop_token) void Game::update(std::stop_token stop_token)
{ {
while (!stop_token.stop_requested()) { while (!stop_token.stop_requested()) {
game_mutex.lock();
player.update(); player.update();
renderer.redraw(); renderer.redraw();
map.check_bounds(player.x, player.y); map.check_bounds(player.x, player.y);
game_mutex.unlock();
std::this_thread::sleep_for(16666us); 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); renderer.clear_screen(0x80, 0x40, 0xFF, 0xFF);
map.draw(player.x, player.y); map.draw(player.x, player.y);

View File

@ -14,6 +14,7 @@ private:
Map map; Map map;
std::jthread update_thread; std::jthread update_thread;
std::mutex game_mutex;
void update(std::stop_token stop_token); void update(std::stop_token stop_token);
@ -24,7 +25,7 @@ public:
void run(); void run();
void draw() const; void draw();
}; };
#endif #endif