Сделал World потокобезопасным

This commit is contained in:
Jiga228
2026-06-28 20:29:19 +07:00
parent 8e09b93f25
commit c95aa557c2
2 changed files with 24 additions and 15 deletions
+13 -7
View File
@@ -4,6 +4,7 @@
#include <unordered_map>
#include <vector>
#include <string>
#include <mutex>
#include "RTTI.h"
#include "Game/Actors/Actor.hpp"
@@ -15,8 +16,9 @@ class World : public ISave
{
GameInstance& game_instance_;
std::unordered_map<std::string, std::shared_ptr<Actor>> actors_map;
std::unordered_map<std::string, std::shared_ptr<Actor>> actors_map_;
std::mutex m_actors_map_;
public:
World(GameInstance& game_instance);
~World() override;
@@ -34,8 +36,9 @@ public:
template<class T, template<class...> class Container = std::vector>
Container<std::weak_ptr<T>> GetActorsByClass()
{
std::scoped_lock lock(m_actors_map_);
Container<std::weak_ptr<T>> list;
for (auto i = actors_map.cbegin(); i != actors_map.cend(); ++i)
for (auto i = actors_map_.cbegin(); i != actors_map_.cend(); ++i)
{
if (RTTI::dyn_cast<T, Actor>(i->second.get()))
list.push_back(std::static_pointer_cast<T>(i->second));
@@ -46,12 +49,13 @@ public:
template<class T>
std::weak_ptr<T> SpawnActorFormClass(std::string name, const Vector3D& loc = { 0, 0, 0 }, const Vector3D& rot = { 0, 0, 0 })
{
std::scoped_lock lock(m_actors_map_);
std::shared_ptr<T> object = std::make_shared<T>();
object->SetActorLocate(loc);
object->SetActorRotate(rot);
std::static_pointer_cast<Actor>(object)->world_ = std::static_pointer_cast<World>(shared_from_this());
std::static_pointer_cast<Actor>(object)->name_ = name;
actors_map.try_emplace(name, object);
actors_map_.try_emplace(name, object);
return object;
}
@@ -60,9 +64,10 @@ public:
template<class T, template<class...> class Container = std::vector>
Container<std::weak_ptr<T>> GetActorsByTag(std::string tag)
{
std::scoped_lock lock(m_actors_map_);
Container<std::weak_ptr<T>> container;
for (auto& i : actors_map)
for (auto& i : actors_map_)
{
if (RTTI::dyn_cast<T, Actor>(i.second.get()))
{
@@ -81,8 +86,9 @@ public:
template<class T>
std::weak_ptr<T> GetActorByName(const std::string& name)
{
auto it = actors_map.find(name);
if (it == actors_map.end() || it->second == nullptr)
std::scoped_lock lock(m_actors_map_);
auto it = actors_map_.find(name);
if (it == actors_map_.end() || it->second == nullptr)
return {};
return std::static_pointer_cast<T>(it->second);