1
\$\begingroup\$

Let me quick explain my actual setup:

I use 2 Threads, one for networking and one for the main-loop (input, update, render). I have two synchronized queues, one for mainthread->networking and one for networking->mainthread. When a chunk of bytes arrives, the network-thread decodes a paket. The network-code knows, what each paket is and what it does. It now creates a functor to change the coordinates of an entity, to spawn a new one, or something else. It emplaces this functor in the queue and the main-tread executes every tick all the functors in the queue.

This kinda works for now, but i think i have to change this completely. I might split up some parts of the main-thread, input for example, and stick it in another thread. Also, i might want to add support for plugins written in lua, python or some other language, and i don't want the main-thread to get stuck when the plugin decides to run a long-running task. This would mean, eventually the main thread has to handle a decent number of queues, one for every thread plus one extra for the other direction (thread->main). Also, at the moment, the networking needs to have all the pointers to the data-structures it wants to control (For example, it has a ptr to the entitymanager stored, so it can create a functor to spawn a new entity in the entitymanager), thats kinda weird.

Are there common techniques to synchronize threads better? Especially since i have to provide a lot more control over the gamestate and still need to synchronize the other threads with the main-thread, i don't really see a better approach other then the functor-queue, so i hope for some suggestions.

\$\endgroup\$
1
\$\begingroup\$

Multithreading in games has always been a difficult thing, hence there are many ideas as how to get stuff done.
I would advice you to use one main thread which is dedicated for drawing and updating entities only (no heavy algorithms or calculations) and one or more (depending on the number of logical CPU cores available) threads which work on AI, physics, etc.
Depending on your needs, you can change that base model. You could for example even make a thread pool, which works on little tasks which you feed to it (which might feel a little like async JavaScript) and then have your main thread render the result. Or you could set constant drawing intervals and have physics, AI,... calculated continously in other threads.
How you go about it heavily depends on what you want to achive and what is the best fit for your scenario.

\$\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.