I’m quite new to SDL2 development, and I have a simple question:
Imagine that my workload is as follows:
I have a main thread, which spawns a new “rendering thread” via SDL_CreateThread(). Then the new rendering thread creates a Window, a Renderer and a Texture and starts the game loop.
Is it possible to change the pixels buffer from the main thread and then the rendering thread show the changes whenever it runs without using any lock?
By “showing” I mean a call to SDL_UpdateTexture() (with the shared pixels buffer) => SDL_RenderCopy() => SDL_RenderPresent().
So, can they really share this pixels buffer? Should I use locks? Should I use a surface instead of a texture?
To answer your question about buffer, yes, this buffer can be shared between threads, but you should be aware of race-conditions.
Doing what you want It will always require some kind of synchronization between threads.
You can go for condition variables (they are not lock free, but you can “try to lock” from render thread without waiting). You can also do this with spinlock in worker thread without locking the render thread (will stress CPU core if you wait too much).
As you can see, there are several scenarios available, but it’s not entirely clear from your message what is appropriate for you.
In the scenario where your render thread just needs to continuously grab a frame from the working thread (you will wait in the working thread for frame to be grabbed but no waiting in the render thread), your best choice is a condition variable.
Why? Will I lose modifications in the pixels buffer (this is ok for me) or it may lead to some kind of internal dead-lock in the SDL or UB?
I mean, I understand that there are races, but what is the worst scenario? To not render the “correct” pixels buffer in one frame I suppose.
What if don’t care that much for this as long as there is no internal dead-lock or get a state where it is undefined behavior for example.
“Doing it right” is what I wanted to say .
If you’re okay with that, the worst-case scenario is partially updated frames. Unsynchronized access is UB, but you’re not gonna to face anything “bad” because it’s just a pixel buffer.
EDIT: assuming your buffer is not being freed/reallocated/etc during this execution.