Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Andrea |
Hello,
i have a custom made path finding algorithm, and since it takes a lot of resources i want it to run in background with a thread.
To avoid the units to stand still too much time the algorithm interrupt himself after a few seconds, it tells what´s the best path up to a certain point, and then evaluate if it is necessary to start another path-finding research to reach the actual target. And so on in a loop.
This is the basic code:
var target
func find_path(start, end):
target=end
if not thread.is_active():
thread.start(self, "calculate", start)
evaluate_path(thread.wait_to_finish())
else:
print("thread still active")
func evaluate_path(p):
if p[p.size()-1]==target:
unit.start_moving_along(p)
print("path found")
elif 0.5*(p[0]-target).lenght()>(p[p.size()-1]-target).length()
unit.start_moving_along(p)
print("getting close, continue from the last point of path")
find_path(p[p.size()-1],target)
else:
print("There is no available path")
func calculate(start):
var path=PoolVector2Array()
path=do_the real_calculations(start, target)
return path
It works fine if the target is reached in the first loop (meaning the sequence of find_path=> calculate=>evaluate).
But for some reason it freeze in the following ones: basically every time it prints path not found yet or getting close it looks like it´s not working on the second thread anymore, because I can no more move the camera and do other in game stuff until the calculation is finished.
Can you help me understand why?
The thread is correctly closed because it doesnt print thread still active
EDIT:
I believe the wait_to_finish() function push another function into the thread: writing evaluate_path(thread.wait_to_finish())
mean that the evaluate function is started into the secondary thread as soon as the pathfinding is finished, and since the evaluate_function is linked to the unit movement, and the unit movement is linked to all the game, all the game start running on the secondary thread, therefore it freeze because the next loop of pathfinding is being processed in the same thread of the game.
Can somebody confirm this?
If yes, how the hell can i make this simple sequence to work?
1-get the start and ending point
2-start a thread
3-run path finding algorithm on secondary thread
4-background calculation reach an end, close the thread
5-examine results in main thread,decide if to start again from point 1