Skip to content

Thread Safe Graphics#924

Merged
bjornbytes merged 8 commits intodevfrom
thread-safe-graphics
Feb 2, 2026
Merged

Thread Safe Graphics#924
bjornbytes merged 8 commits intodevfrom
thread-safe-graphics

Conversation

@bjornbytes
Copy link
Owner

@bjornbytes bjornbytes commented Jan 27, 2026

This branch makes a lot of graphics module functionality thread safe. It just guards the global command buffer with a mutex. It allows threads to create/read/write buffers, textures, materials, meshes, models, shaders, etc. There isn't any noticeable overhead for single-threaded usage.

I tested this by creating a bunch of threads that call newTexture in a loop, and didn't see any crashes, corrupted stats.textureMemory values, and TSAN didn't complain about anything. So that's a good sign I guess.

Pass is pretty much already thread safe, so it should already be possible to record multiple passes from multiple threads.

There are a couple of remaining TODOs before this can be merged:

  • Pass tally stuff will deadlock in lovrBufferCreate
  • Window texture
  • getLayout needs to be thread safe (it can probably just use global lock?)
  • Make Font atlas thread safe (for now, just put a lock on Font. readwrite lock could be cool)

Also, a separate but related change is to change lovr.graphics.submit to use multiple threads to record passes, and also add a method on Pass to ask it to start recording its command buffer right away. This could impact things, because now recordRenderPass and recordComputePass would need to start locking things instead of assuming the lock is already held.

@bjornbytes bjornbytes linked an issue Jan 27, 2026 that may be closed by this pull request
@bjornbytes
Copy link
Owner Author

Tried using multiple threads to record passes but it's not really worth it. Even in a really favorable use case (lots of passes with lots of draws), and after removing all the locks, I was only able to get around a 2.5x speedup in lovr.graphics.submit, with 16 threads.

It's still probably useful to merge what's here though (letting people use graphics module from any thread). I found one more thread safety issue to fix though, lovrPassGetBuffer calls gpu_buffer_init which needs to be locked. Might just use a lock in core/gpu for the allocator and morgue.

@bjornbytes bjornbytes merged commit 03bf43f into dev Feb 2, 2026
12 checks passed
@bjornbytes bjornbytes deleted the thread-safe-graphics branch February 2, 2026 01:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow to create materials,textures, models in threads.

1 participant