Skip to content

Instantly share code, notes, and snippets.

@willnationsdev
Last active July 31, 2018 16:16
Show Gist options
  • Save willnationsdev/d914fd2382764e957e3f46c22b2e8278 to your computer and use it in GitHub Desktop.
Save willnationsdev/d914fd2382764e957e3f46c22b2e8278 to your computer and use it in GitHub Desktop.
GDScript threading example with an asynchronous "blocking" OS.execute that doesn't block the main thread.
extends Node
signal thread_finished(t)
var t
func _ready():
t = Thread.new()
connect("thread_finished", self, "_on_thread_finished")
var params = {
"thread": t
# whatever you want in here
}
t.start(self, "_thread_method", params)
func _thread_method(p_params):
# do stuff with p_params in a thread.
# For example, a synchronous OS.execute that DOESN'T block the main thread.
var output = []
OS.execute(p_params.command, p_params.args, true, output)
emit_signal("thread_finished", p_params)
func _on_thread_finished(p_params):
if p_params.has("thread"):
p_params.thread.wait_to_finish() # only synchronously execute the signal callback code
# ^ note that you need this 'wait_to_finish' call or else the thread will never be rejoined with the main thread.
# You'll end up with Object instances still active at exit if you don't call it (gives you warnings at exit).
@willnationsdev
Copy link
Author

Noticed I'd need to change the var t into a member variable so it wouldn't be de-allocated once _ready() completes (it's a Reference variable). Whoops.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment