Search code examples
cgraphicssdlrace-conditionnon-deterministic

Does this SDL_gfx code involve a race condition?


When I run the following code on my machine, it doesn't behave deterministically. The triangle it should draw only appears sometimes:

#include <SDL/SDL.h>
#include <SDL/SDL_gfxPrimitives.h>

int main(int argc, char* args[])
{
    int xres = 250;
    int yres = 250;

    SDL_Surface* screen = SDL_SetVideoMode(xres, yres,
        0, SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_NOFRAME);

    SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
    filledTrigonRGBA(screen, 10, 10, 170, 170, 75, 100, 255, 0, 255, 255);
    //SDL_Delay(1);       // this fixes some race condition?
    SDL_Flip(screen);
    SDL_Delay(1000);
    SDL_Quit();

    return 0;
}

But if I uncomment the first SDL_Delay() call, the triangle always appears. I have also observed this when using SDL 2.

Is there a race condition in one of the libraries here, or is something wrong with my computer?


Solution

  • There are many things involved, especially if you have compositing window manager. Like if you flip your resulting image but window wasn't visible at that moment. With compositing it is even worse since it implements its own double buffering.

    Just repeatedly draw it a loop, like every single example does. If you absolutely have to, you can redraw only on window events (mostly 'exposed' one).