Multithreading and Rendering

Godot Version

Godot 4.6.2

Question

I have been using multi-threading in Godot for the procedural forest system in my game for over a year now. It loads chunks on a background thread, and then uses call_deferred to add nodes to the scene tree. I have also experimented with versions using RenderingServer and there seem to be similar problems either way.

Occasionally, I get crashes, and I have isolated it to the multi-threaded forest system (remove that system and the crashes go away). These crashes do not register any error or warning message in the editor, when running the game through the Godot editor.

My core question: Can 3D rendering nodes be created/instantiated on a background thread, and then added to the scene tree with call_deferred() ?

The docs clearly say this can be done, but perhaps this is not completely safe when creating Rendering nodes like MeshInstance3D?

I have read this document many times, and I am confident that my code is using mutexes/resources in the proper way:

Are either of these scenarios OK, running on a background thread or WorkerThreadPool?

Example, creating a mesh instance 3D:

func some_threaded_function() -> void:
    var mesh_instance := MeshInstance3D.new()
    # SOME_MESH_RESOURCE is preloaded(). is that a problem
    mesh_instance.mesh = SOME_MESH_RESOURCE
    
    some_node.add_child.call_deferred(mesh_instance)

Example, instantiating a packed scene that has 3D rendering nodes inside:

func some_threaded_function2() -> void:
    # SOME PACKED SCENE contains rendering nodes, like MeshInstance3D or MultiMeshInstance3D
    var scene := SOME_PACKED_SCENE.instantiate()
    
    some_node.add_child.call_deferred(scene)

I’m kind of at my wits end trying to figure out where crashes are coming from, and I think it’s coming down to this line in the docs:

Instancing nodes that render anything in 2D or 3D (such as Sprite2D or MeshInstance3D) is not thread-safe by default.

And it sounds like the Separate threading option is not really recommended for production.

Thanks,

Mike

Yeah, depends on your code. Threads are good for background math and management but as stated connecting with rendering will require main-thread activity

So is this a firm statement - we can never instantiate/create nodes that are involved with rendering on background threads?

It’s just hard to distribute the load of spawning large worlds if we don’t do that.

I’m pretty sure I need a clean delineation between chunk data and a visual representation layer (main thread), but I dread the refactor to do so.

You can safely create nodes and assemble them into orphaned branches in a thread. Only the communication with the scene tree object is thread unsafe and needs to be done on the main thread. So only the final addition of the top node of such a branch to the main tree needs to be done on the main thread or via a deferred call. The thread-safety page you linked from the docs also confirms this:

However, creating scene chunks (nodes in tree arrangement) outside the active tree is fine. This way, parts of a scene can be built or instantiated in a thread, then added in the main thread:

Note that if you instantiate a packed scene you need to take care there’s no thread unsafe code in node constructors. Those will run on instantiation.

I understand that, but the issue is instantiating rendering nodes seems to hit the main thread (very next section of the docs discusses it).

Can you show a minimal example that demonstrates it?
If there is a lot of rendering data that needs to go to the gpu in one frame, consider splitting that data and distribute the gpu upload through frames.

Unfortunately, minimal examples do not seem to bring out the behavior. Only when I push the system to the limits (hundreds of thousands of trees), do I see the occasional crash.

And edit: I am using several LODs, so just to be clear I am not generating/rendering hundreds of thousands of full fidelity trees.

I’ve done quite a lot of debugging to confirm that the crash is linked to the multi-threaded forest system (when I run the forest system on the main thread, it is quite slow, but does not crash the game).

I’ll keep poking around and update this thread if I can create a minimal example. Seems like I’m going down the road of refactoring code anyways.

Those should be handled via multimesh instance node(s).

They are - that really isn’t the issue here. I do not want this conversation to veer off track. I am curious if anyone else has experienced issues trying to create/instantiate rendering nodes on background threads (either worker pool or manually created thread).

I spent some time digging into the C++, and I think I’ve found the answer here.

I’m not seeing any possibility that creating rendering nodes (such as MeshInstance3D) is safe to do on a thread:

Immediately inside the VisualInstance3D constructor, we can see that we are hitting the RenderingServer, trying to create a rendering instance and attach the object ID to it. So doing this on another thread is definitely not a good idea.

Are you sure this is the cause of crash? I’d expect rendering server calls to be thread safe, more or less.

I am quite sure at this point. I think Godot devs have some plans to make rendering server thread-safe, but it isn’t currently thread-safe. There is the threading “Separate” option but it triggers warnings and generally makes me feel uneasy about it.

Tonight I refactored my code, removing node instantiation/rendering server instance create calls onto the main thread, and I hammer tested my forest system flying around at 200 m/s and no crash.

One (maybe two, but I don’t remember off-hand) of my games loads meshes in a background thread. It returns to the main thread at the moment of instantiation, though.

Yep- and as odd as it is, I believe resource modification is fine on a background thread (so long as nothing else it touching the resource during modification).

But I think instantiation/adding to the scene tree is where trouble comes in.

I don’t remember ever having problems with creating meshes via rendering server in a thread. Adding to the tree is different matter though. I always do that in the main thread.

Loading is fine, but instantiation cannot occur in a thread. The add_child() method MUST happen on the main thread, as it is not thread-safe.

Just another note here - Mesh (Resource) is not the same as MeshInstance3D.

It’s pretty clear from the engine’s source that as soon as the MeshInstance3D node (or any visual node) is instantiated it hits the rendering server and tries to bind an object to it.

They both touch the server. A resource will typically exchange a lot more data with it than an instance. So if the assumption is that touching the server causes the crash, the resource would have more chance to do it.

I made a little test. It perpetually creates and deletes a bunch of mesh instances. Nothing happens, ticks like a clockwork:

func _ready() -> void:
	WorkerThreadPool.add_task(
		func() -> void:
			var nodes := []
			while true:
				nodes.map(func(n): n.free())
				nodes.clear()
				OS.delay_msec(20)
				for i in 100:
					nodes.append(MeshInstance3D.new())
				OS.delay_msec(20)
	)

I would think that your 20ms delays provide plenty of time for the renderer to not get choked in this simple example.

Unless we get someone from the rendering team to chime in, I think the general guidance given in the docs should overrule doing this:

Instancing nodes that render anything in 2D or 3D (such as Sprite2D or MeshInstance3D) is not thread-safe by default.