Nazaj na multithreadanje - fonti
This commit is contained in:
@@ -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;
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user