+4 votes

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 :-)

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

in Engine by (162 points)
edited by

3 Answers

–16 votes

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.

by (715 points)

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.

+5 votes
by (431 points)
+1 vote

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...

by (1,350 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.