1
\$\begingroup\$

This has been a question that has always troubled me while thinking about the code and logic behind gaming, I was wondering when and when not, is it appropriate to create new threads for different tasks or how should I handle long tasks that could potentially freeze my game?

The first situation I could think of would be the rendering and the update loop. My thought behind this is that keeping these two seperate would prevent update problems because of a low frame-rate so even if the frame rate is changed there would still be a consistent update cycle.

The second situation is somewhat more specific and is just an example but say my game has multiple building components that can be placed over the world and my game updates them every second or so to check maybe if they are floating (if they have physics) or maybe if it's environment has changed, should this update cycle also be in another thread because it could take a long time?

How about if I was pinging a client, would my server not freeze whilst waiting for a response? Is this another situation where threads should be created? or is there another technique that I should be using to enhance performance and efficiancy?

\$\endgroup\$
  • \$\begingroup\$ Well first, games very rarely do something that wpuld freeze them other than pinging and such. Networking, physics and rendering should have it's own thread. \$\endgroup\$ – Bálint Dec 6 '16 at 7:52
  • \$\begingroup\$ Instead of threading Draw() vs Update(), you can just add some logic to skip draw calls. So your Update() runs at 60fps all the time, Draw() runs at 60fps when it can. \$\endgroup\$ – lozzajp Dec 6 '16 at 9:22
  • \$\begingroup\$ Possible duplicate of Avoid threads/multithreading \$\endgroup\$ – Philipp Dec 6 '16 at 12:22
1
\$\begingroup\$

First of all IO should be asynchronous. A roundtrip (client-server-client) can easily take up to 200 milliseconds (especially when crossing oceans). That is time you just cannot afford to be simply waiting.

Asynchronous means that you set up a event to be triggered/pushed to the queue/... by the OS as the packet arrives or the disk read is complete. Then every frame you check if it is complete and then handle the result.

Next tasks that don't need to complete in the same frame they are started in (for example a path search for a mob that has a reaction time/animation) should be split up into smaller chunks. This will require a bit of rewriting to make sure that any state that needs to carry over from chunk to chunk is preserved and passed along properly.

Threads can be more of a burden than a help because the overhead of synchronizing the tasks and guarding against data races can easily overtake any benefit multithreading could bring.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.