Advertisement

should ai code go in its own thread?

Started by October 06, 2010 05:00 AM
0 comments, last by KulSeran 13 years, 11 months ago
is it better to put enemy ai code in its own thread while the render thread can just coninue without any need to stop and wait for the ai player think code to complete?, because things like stop , rotate, go in the direction he is facing and then stop again takes up cpu time right?
:)
No, and yes. Forget about threading off "subsystem X" and start thinking about threading off "task Y". And, unless you KNOW you are going to hit a CPU limit in your game, forget about threading, as it is a huge complication if you don't actually need it. But, if you KNOW you are going to hit a CPU limit, write everything knowing you are using threading since adding threads late in the project is a complete mess.

First off, the GPU will continue to chug away on its own. The actual drawing happens in parallel to your code. Calling something like glDrawElements() just queues up the commands to draw, and isn't actually doing the drawing right then and there.

Secondly, your rendering code saps CPU to send commands to the GPU, and it also needs to know information about what it is rendering. This means you have to synchronize the game code such that the AI can't update it at the same time the rendering code wants to read it. The best solution usually results in you double buffering any shared data, so the synchronization can be done with a single lock and swapping a buffer pointer.

Thirdly, in general you don't want the AI in one thread, as that doesn't gain you much. You want a thread pool that you can hand off AI tasks to so that you get ~1 thread per cpu core, and your entity's AI updates are then spread across all cores. This means your AI has to be thread safe as well.

Lastly, even the graphics stuff can be threaded. Objects need to be visibility tested, sorted by depth (for alpha or to reduce overdraw), vertex and instance buffers updated before you can upload them to the graphics api. etc. There are a lot of small tasks here that you could also throw into a thread pool.

This topic is closed to new replies.

Advertisement