SDL_CreateRGBSurface in second thread?

Hello,
I have a question: Is it possible to call SDL_CreateRGBSurface and SDL_CreateRGBSurfaceFrom in second thread? They only load buffer and set R,G,B mask.
Also asking about IMG_Load() From SDL_image library. They use libpng or libjpeg for example to create buffer from image file and after that they Create Surface.

My task is to create Texture form png. To that moment i load buffer using libpng in second thread and after that in main thread i use opengl to create texture. And now i want to migrate to SDL and is it possible to
IMG_Load to SDL_Surface in second thread and after that in main thread to CreateTexture using SDL_CreateTextureFromSurface?

I have progress about this question i create simple program to test this case
here is thread function:

Code:

static void
load_texture()
{
SDL_Surface *surface = nullptr;

std::cout << "THREAD STARTED!\n";
while (true)
{
    surface = IMG_Load("images/wheel/background.png");
    if (surface == nullptr)
    {
        std::cout << "ERROR LOADNING SURFACE!!!\n";
        
    }
    SDL_FreeSurface(surface);
    usleep(5000);
}
std::cout << "THREAD END!\n";

}

And i have no problem with drawing and loading for past 10 minutes

I asked the same thing about IMG_Load a while back and I got the answer that it’s safe to call IMG_Load in another thread and then call SDL-specific functions (SDL_CreateTextureFromSurface for example) in the main to create the final texture.
I am using this exact solution when I create a texture in my framework. :slight_smile:

Short answer: it’s safe to execute IMG_Load in another thread and SDL-specific functions should be executed in the thread that created the SDL-window, which is usually the main thread.

But, it is safe to call IMG_Load in multiple threads simultaneously? I am trying to load about 20 surfaces at a time, but in some scenarios it crashes.

Multithreading is useful when you have compute-intensive code that you want to split up among multiple CPUs. For loading files, the CPU work will be dwarfed by the disk access time, so you’re not really going to save much time by doing it this way. You’d be better off just loading those files all in the same thread, one after the other.

This does not answer his question and I don’t think it’s necessarily true either. Especially PNGs take noticeable time to decode, and disks (SSDs) are very fast nowadays.

No idea about the crashes, I think it should not crash, maybe try to figure out the reason with a debugger?

I was working with the 2.0.4 version of libsdl. Nwo I’ve updated to version 2.0.8 and everything works perfectly fine. No crashes at all!
For your information, by loading the files in multithread I am now saving above 20% of time.
My game loads about 2000 images in the initialization, that’s why this gain is so important for me now.
Thank you!

1 Like