Nazaj na multithreadanje - fonti

This commit is contained in:
2026-03-12 16:18:51 +01:00
parent 834f0b29c3
commit 74159a6fda
20 changed files with 254 additions and 43 deletions

View File

@@ -4,20 +4,27 @@
#include <memory>
#include <utils.hpp>
#include <object/entity.hpp>
#include <mutex>
namespace Game::State {
class GameState {
public:
static GameState& getInstance() { static GameState instance; return instance; }
// Retrieve a REFERENCE of the entities; DANGEROUS!
std::vector<std::unique_ptr<Object::Entity>>* getEntitiesRef();
// Update entity at index, by REFERENCE
Object::Entity* getAtIndex(size_t at);
// Execute work while holding the GameState mutex to keep access thread-safe.
template<typename Fn>
void withEntitiesLocked(Fn&& fn) {
std::scoped_lock lock(mMutex);
fn(mEntities);
}
// Update entity at index, by REFERENCE.
Object::Entity* getAtIndex(size_t at);
// Add an entity to the gamestate.
void addEntity(std::unique_ptr<Object::Entity> entity);
private:
mutable std::mutex mMutex; // Shared mutex for thread safety
std::vector<std::unique_ptr<Object::Entity>> mEntities;
};
}