Last active
July 31, 2018 16:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.