I’m am making a turn-based game where enemies will calculate and execute their moves one after the other. When testing the game on a less powerful config I noticed a significant FPS drop when an enemy was calculating its move. Everything is done on the main thread, there are a lot of calculations involved, so it doesn’t surprise me much.
So I thought it was time to use Threads. However I noticed that Threads were supposed to be used as a continuous background process , like loading 3D terrain, not waiting for an AI to finish calculations spread over multiple frames.
Then I tried to use await get_tree().process_frame to manually spread the workload on different threads, but something is rubbing me the wrong way about this approach, I feel like I’m making a mistake.
I would appreciate the thoughts of someone more technical than me on this issue. Do you think it’s okay to use asynchronous functions to maually split the calculations over multiple frames or is it better to use threads? If you recommend using threads, my question is, do I use one Thread for all the AIs or do I use one thread per AI (the number of AIs is expected to be around 16)
Threads can absolutely be used to parallelize your calculations, they are not usually infinite background processes. One thread per AI sounds good if there are around 16 or lower, 50 for example might border on too many, all depending on the player’s system.
You can create a thread for each AI and call wait_to_finish() over all of them to ensure the work is done before the results are needed.