Gdnative C++ multithread create arraymesh.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jujumumu

I’m making a game where I need to be able to create meshes in separate threads in gdnative. In Rendering I have the thread model set to Multi-Threaded. The code is what I am running to test this.

void makeaaraymesh() {
        for (int i = 0; i<50000; i++) {
            Ref<ArrayMesh> terrainamesh;
            terrainamesh.instance();
        }
        Godot::print("ALL DONE");
}
//In init
for (int i=0; i<4; i++) {
        workers[i] = std::async(std::launch::async, &makeaaraymesh, this);
}

The error that occurs is always EXC_BAD_ACCESS. This should be thread safe since I have the Rendering thread model set to Multi-Threaded. Am I doing anything wrong?

In the thread safe API docs it says.

Instancing nodes that render anything in 2D or 3D (such as Sprite) is not thread-safe by default. To make rendering thread-safe, set the Rendering > Threads > Thread Model project setting to Multi-Threaded.

Note that the Multi-Threaded thread model has several known bugs, so it may not be usable in all scenarios.

Is this just one that doesn’t work?

I would advise you don’t do this in Godot 4 as per mentionned in the docs, and also other people seem to have had issues. Sometimes the problem is not just crashes, but it turns out to be slower. If you need to generate meshes I would build the geometry in separate threads and create the mesh resource on the main thread. That’s what I do in my voxel engine and it is fast enough.

The real problem I had with this model was actually physics, because it is simply not thread safe and is also the most expensive to build.

Note: as I have seen from other reports it is also possible that something in GDNative itself is not thread-safe. Some people have tried using things that definitely should work in separate threads, but do not in GDNative.

Zylann | 2022-02-11 13:37