[SDL] Blitting / event handling with multiple threads
stephane.marchesin at wanadoo.fr
Mon Jan 31 12:18:19 PST 2005
Christian Morgner wrote:
>I'm trying to write a clone of an old DOS game in C++, using SDL,
>and I've been working on that for about a year now, having tried
>many different methods of event handling and drawing.
>I first tried a structure where there was only one game loop that
>was drawing the objects, updating them and handling input events.
>Using a double-buffered video mode, the loops/sec of the whole game
>were limited to approximately the refresh rate of my monitor, because
>SDL_Flip waits for the vertical retrace.
>The game got more and more complex (and slow), because there were
>hundreds of objects that had to be updated and blitted, so I tried to use
>multiple threads to speed up the game. Unfortunately, SDL doesn't
>support blitting and event handling in any other thread than the main
>thread, so any speed improvement is lost because event handling and
>drawing are limited by SDL_Flip() again.
>Is there any possibility to call each object's draw() method (where a lot
>of blitting is done) from a separate thread, so that only this particular
>thread has to run at 60-80 loops/sec. and the other ones are only
>limitated by the CPU speed?
I'll tell you a secret : even if you have 100 threads, you still have 1
video card. Which means, basically, that it will be serializing graphics
access at some point.
So there's no point in multiple threads rendering to only one graphics
card. Thus the following limitation usually exists in the graphics world
and isn't really bothering : only the thread that created the graphics
context should draw to it. That's also true for SDL : the thread that
initialized SDL (main thread) should do the drawing. Lots of APIs have
that limitation btw.
>My last try was the following one:
>I created three threads where game objects can register themselves,
>and the thread objects call their draw() / update() / event() method
>The drawing thread also calls SDL_Flip() and SDL_Delay(10) to synchronize
>with the vertical refresh, so it is the only one that is slowed down, but the
>SDL docs say that it is not safe to call any library function outside the main
That's true and false depending on the library. If you're not sure what
your library can handle, you have to go with the pessimistic asumption.
That said, lots of libraries have been becoming reentrant recently so
the situation is clearly improving. These libraries usually advertise
themselves as such (because it sometimes takes them a big code cleanup
to become so :).
More information about the SDL