I developing a simple real-time strategy game in a small team with no experience, and we're considering using one thread per game object (tank, soldier, etc). Is this a good idea or is it overkill?
The thread would call each object on each instant change (game timer, not graphic engine timer)
We're using Python with the Panda3D engine, meaning the GIL is probably going to reduce a lot the possible speed improvements.
Answer
Rule number one of multithreading: Don't even think about it, unless you really need to use multiple CPU cores for performance reasons*. Multithreading opens up a whole can of worms of obscure and impossible to reproduce bugs:
- Race conditions! Because you have no control over the thread scheduling of the OS, you have no control over the order in which things happen. You might assume that a certain task takes much longer to complete than another and build on that assumption. But in one of a million executions that assumption is wrong, and an obscure bug happens which is impossible to reproduce.
- Synchronization issues! When one thread modifies data while another thread is in the process of reading it, the thread reads a mixed state of old and new data. This can lead to really obscure bugs which are - again - almost impossible to reproduce.
- Deadlocks! The two problems above can be avoided by certain synchronization and locking techniques which are available in most programming languages. Unfortunately these features take a lot of knowledge and experience to use correctly. When you use them incorrectly, you will quickly run into deadlocks: Two threads both blocking their data structure and both waiting for the other thread to release theirs. This will lead to an infinite loop and cause both threads to freeze.
When you and your team are inexperienced, do it without multithreading. You will run into enough bugs and architecture problems without the additional complexity nightmares brought to you by unnecessary threading.
The great age of real-time strategy games were the late 90s in which there were practically no multi-core CPUs on the consumer market. Tons of great RTS games (Command&Conquer, Age of Empires, Total Annihilation, Starcraft...) did well without multiple cores on much worse hardware than you have today. So why shouldn't you be able to do the same?
*) Exception from this rule: Waiting for I/O of files, network or user input. But in that case you shouldn't write your own multithreading code. Use the asynchronous APIs with callbacks provided by the standard library when you can. These use multithreading "under the hood", but hide the nasty details from you.
No comments:
Post a Comment