should ai be calculated in its own thread?

Anddos 103 Oct 06, 2010 at 10:15

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?

3 Replies

Please log in or register to post a reply.

TheNut 179 Oct 06, 2010 at 12:03

Ideally you should be adopting parallel programming as often as you can. It’s the future of software development. Do keep in mind however that AI shouldn’t bog down performance even if it were single threaded. I only say that because if your algorithms do consume a lot of processing time, then you might need to reevaluate them, regardless if you thread logic or not. Typically AI decisions are synchronized with some sort of clock too. A decision is made every frame (or 33 milliseconds) for example. So even if you thread logic, the logic itself won’t execute continuously.

Check up on thread pools and how you can use that to perform asynchronous operations. This way you can control the number of active threads based on your requirements and the hardware available.

alphadog 101 Oct 06, 2010 at 15:13

Better? Probably (but not assuredly) yes. Easier? No.

Your problem, with current popular languages, is going to be coordinating the effect of parallel-running tasks over the shared data structures. Welcome to lack of determinism, race conditions, synchronization issues, etc! :) Or, alternatively, you will have to learn a new language like Erlang or Scala.

Stainless 151 Sep 20, 2012 at 08:58

Ok think of the case where the AI moves some game pieces around. The AI is running in it’s own thread.

While the AI is moving the game pieces around, the games draw routine is called.

The AI hasn’t finished it’s run, so some pieces are in the right place, and some are in the wrong place. It’s even possible for one of the coordinates of a piece to have been updated but not the others. This will produce horrible on screen artifacts.

So you need to plan for this situation and have a way of handling it.

An even more dangerous example is when you have AI and physics running in their own threads. Hell that can go wrong spectacularly