I've made a path finding manager to get a path via a thread.
It works, but is there any way it can go wrong ?.. I haven't tried it with a lot of instances. I am worried that there may be come sort of screw-up if there a lot of threads.
Manager Class (header)
Code: Select all
#pragma once
#include "newAStar.h"
#include <queue>
#include <memory>
class PathRequest
{
public:
std::future<std::vector<Vec2f>> thread;
class Actor* owner = nullptr;
PathRequest() = default;
};
class PathfindingManager
{
private:
std::vector<PathRequest*> m_queue;
// for threading
static MyAStar* m_pathFinder;
static std::vector<Vec2f> _getPath(Vec2f start, Vec2f end);
public:
PathfindingManager() = default;
~PathfindingManager();
PathfindingManager(vec_int_map map, Vec2f celldims);
void requestPath(Vec2f start, Vec2f end, class Actor* owner);
void checkForDone();
};
Code: Select all
#include "PathManager.h"
#include "GamePiece.h"
MyAStar* PathfindingManager::m_pathFinder = nullptr;
// function for thread
std::vector<Vec2f> PathfindingManager::_getPath(Vec2f start, Vec2f end)
{
return m_pathFinder->getPath(start, end);
}
PathfindingManager::~PathfindingManager()
{
if (m_pathFinder)
delete m_pathFinder;
for (auto& it : m_queue)
delete it;
}
PathfindingManager::PathfindingManager(vec_int_map map, Vec2f celldims)
{
m_pathFinder = new MyAStar(map,celldims);
}
void PathfindingManager::requestPath(Vec2f start, Vec2f end, Actor * owner)
{
PathRequest* req = new PathRequest;
req->thread = std::async(_getPath, start, end);
req->owner = owner;
m_queue.push_back(req);
}
void PathfindingManager::checkForDone()
{
if (m_queue.size() == 0)return;
for (int i = 0; i < m_queue.size(); i++)
{
if (m_queue[i]->thread.valid())
{
std::vector<Vec2f> p = m_queue[i]->thread.get();
if (p.size() > 0)
{
m_queue[i]->owner->SetPath(p);
delete m_queue[i];
m_queue.erase(m_queue.begin() + i);
i--;
}
}
}
}