Is it thread-safe to render inside event watcher?

Hello everyone!

I have read the github discussion about the main thread being blocked while moving or resizing the window on some platforms. If I understand correctly this will not be an issue in SDL3 if you use the main callbacks.

My question is about the proposed workaround when using the traditional approach where SDL_PollEvent is called manually (which is the only option in SDL2).

slouken wrote:
I’ve added a solution that dovetails nicely with the new main callbacks in SDL 3.0 and if you’re not using that you can set an event watcher to handle expose events and draw then.

There is also an example that uses this approach. It uses SDL_AddEventWatch to register a callback that ends up calling a bunch of render functions (including SDL_RenderPresent).

The wiki page for SDL_RenderPresent says:

“You may only call this function on the main thread.”

The wiki page for SDL_AddEventWatch says:

“WARNING: Be very careful of what you do in the event filter function, as it may run in a different thread!”

Am I missing something, is there perhaps an undocumented guarantee that the event watcher will always be invoked on the main thread when dealing with window events, or is this simply not thread-safe?

That particular event will only happen on the main thread, so it’s safe to render in response to that event. Other events may happen on other threads, so it’s not safe in general to render from an event callback.

1 Like

Thank you for the clarification.

Is somewhere a list of events that can only happen in the main thread?

One reason why window rendering may be done in an event watcher is because the window is repainted as it stretches. One of the solutions is the SDL_WINDOWEVENT_RESIZED event watcher and rerendering of the window content from a callback (example). Even though this works properly, it is difficult to know whether it is completely safe.

It would be useful to have a table in the documentation describing which types of events may come from which threads, what is safe and what’s not.

1 Like