How do you execute multiples functions simultaneously?


Got a programming question today. How would I run multiple functions/execute commands at the same time? What I'm basically getting at here relates to games. Lets say you have a game where you have 2 tanks. An enemy comes into view, they both turn and fire, but at the same time. In the code I've been used to writing, it seems that if you were to achieve them doing this, commands to turn and to fire would need to be executed at the same time. I suppose you could write a function that would govern all of the motion for the game, but that seems like it might get bulky quickly, especially if its a big game. How would you  do this?

Thanks for answering!
If you answer specifically in one programming language or another thats ok, b/c I'm familiar with several! Just need something to set me on the right track here!

lemonie5 years ago
You need to use a clock/time function.
I.e. You have a loop like:
Tank 1 input
Tank 2 input
Function the shots and positions

Yes you can both destroy each other simultaneously, the shot function loops for each iteration of movement.

kelseymh5 years ago
As Rick said, you can't get "simultaneous" execution unless you have more than one processor (or core).

You can get "approximately" simultaneous execution if you compiled and linked your code as multithreaded, and took care to code up the necessary mutex locks in each function.

You may also choose to write your code as interrupt driven, or using a real-time operating system, but those methods rely on having appropriate hardware for execution.

Use the terms above to begin your search for more detailed information appropriate to your application.
rickharris5 years ago
For the most part you can't. Unless there are 2 processing paths (dual core or better) then a single processor will process one command at a time.

HOWEVER they do this so fast (10,000's or even 100,000 of instructions per second) it appears they do several things at once.

With so little time between instructions the chance of the first polled always getting selects are slim.

In general good code is written as a series of functional modules i.e. a section of code that does something unique. these modules are then called at the appropriate moment into action.

This way the main sequence is a series of calls to other areas made depending on the current state of play. So a module that needs to check for key presses will be called often to make sure it captures them whereas a module that deals with the results of te player being hit will ONLY get called when that action happens.