SFML community forums
General => General discussions => Topic started by: Aster on December 11, 2012, 05:58:14 pm
-
Hi y'all!
I've been writing a game for a while, and I figured it'd be time to switch to multithreading, and maybe improve the overall FPS of the game.. However, in my long session of thought, I got stuck on one thing:
How do you "communicate", or pass information, between threads?
I know that if a variable is accessed by two threads at once, then the program crashes, and I've been told to use mutexes. But don't mutexes destroy the idea of speed? Don't they just make the program slower?
How do you guys work around this?
Cheers, and thanks in advance;
Aster
EDIT: Before I get told to post this stuff in the sf::System forum; I'm not having a problem with sf::Threads, this is more or less a general question.
-
I've been writing a game for a while, and I figured it'd be time to switch to multithreading, and maybe improve the overall FPS of the game..
If you don't have an actual performance problem, "switching to threads because I heard they make things faster" is a bad idea. Note that multithreading introduces a complexity which has to be justified.
I know that if a variable is accessed by two threads at once, then the program crashes
That is wrong. Concurrent write or write/read accesses can lead to race conditions. They may result in data corruption, but not necessarily program termination.
But don't mutexes destroy the idea of speed? Don't they just make the program slower?
You should really read more about the concepts of multithreading, instead of just believing single sentences you have heard. Of course mutexes have a performance overhead, that is why you only lock when necessary.
-
Depends how the system is set up. As a rule threads should share as little data as possible. And that data either needs locking (slow) or to be read only (limiting).
The common is either a task system where discrete functional logic is pushed off to be handled by a set of threads, or for data to be passed around the system in a series of queues, like a production pipeline for logic.
The former is easier to ad hoc into existing code and designs. The latter tends to be a cleaner design IMHO, but needs the system built in that way from the start. Neither are without issues.
One big issue games have is they are very stateful by nature. I tend to think state should be avoided or minimised where it can, but with games this is tricky. This makes multithreaded code tricky. Plus if your system isn't built for threads from the ground up you may not even see a significant increase in performance. It may even decrease.
-
Yeah, multi-threaded game engines only appeared quite recently. For your first few games, don't bother with it, you'll understand in time how they can be useful.