How to properly use threads ?

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

I’ve seen you could create threads in GDScript but there’s a big lack of documentation about them…
I struggle to properly understand their uses, I would like to know what I can do and cannot do with that. If someone could enlighten me, thank you :slight_smile:

EDIT : I just need some technical informations and, why not, some concrete use cases. Thanks :slight_smile:

:bust_in_silhouette: Reply From: duke_meister

If you don’t know why you need to create threads then you probably don’t need to.

If you have a long-running task that can run ‘in the background’ while your main code is running, then you can look into it. An example could be an ‘expensive’ calculation that would perhaps make your UI or the rest of your game freeze or be sluggish. Even so, just running it in a thread might not help.

Many people think they will magically speed up your code. But just creating threads because they are cool could well slow your code down.

It’s a tool offered by the engine, and it’s a proper understanding of it that will actually decide either I need it or not.

In fact, I’m not unfamiliar with threads, as I already had to make a project on the C++ Qt framework which was partially relying on them. But I’m not familiar with the paradigm Godot is using so I expected a more technical approach on threads mechanisms for this particular engine, because the way to use the threads here and the reasons that push you to create them seem to be different of what I was used to.

snk | 2018-07-05 06:46

:bust_in_silhouette: Reply From: hungrymonkey

Godot demo project

doc on how godot is threaded

:bust_in_silhouette: Reply From: Xrayez

As for the use case, I’ve recently realized the need in using threads when I stumbled upon the problem of generating world chunks procedurally where generating a chunk could exceed the delta time. Basically I applied some basic mechanism to let world chunks generate themselves in the background. It didn’t speed up generation in general but the freezes almost went away.

I’ve encountered several other issues with using threads, like ensuring that resources are accessed on the right time to avoid deadlocks etc. Say you want to get access to the same texture, different threads could try to access it, so I’ve become familiar with mutexes to try to resolve this issue:

# read/write something

This is actually my first experience with using threads so I’m still figuring this stuff out…