multithreadingraylib

Using threading to load textures in Raylib is failing


If I load textures without threading in Raylib it works fine:

INFO: FILEIO: [assets/spades/5_spades.png] File loaded successfully
INFO: IMAGE: Data loaded successfully (112x176 | R8G8B8 | 1 mipmaps)
INFO: TEXTURE: [ID 46] Texture loaded successfully (112x176 | R8G8B8 | 1 mipmaps)

If I call the function to load textures inside a thread, it fails:

INFO: FILEIO: [assets/spades/7_spades.png] File loaded successfully
INFO: IMAGE: Data loaded successfully (112x176 | R8G8B8 | 1 mipmaps)
WARNING: TEXTURE: Failed to load texture

however it doesn't say why it failed to load the texture.

I've published the source code here: https://github.com/imekon/RaylibThreading


Solution

  • Raylib is a wrapper around OpenGL, and the underlying OpenGL context doesn't support being accessed from multiple threads concurrently.

    you need to load the images into memory as an Image using LoadImage in the second thread, then in the main thread create a texture from it using LoadTextureFromImage.

    Textures are stored in GPU memory and can only be created by the main thread in Raylib, while images are stored in RAM and can be created and destroyed by any thread. (You still need synchronization if you are sharing images between threads)