thread.gd 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. extends Control
  2. var thread: Thread
  3. func _on_load_pressed():
  4. if is_instance_valid(thread) and thread.is_started():
  5. # If a thread is already running, let it finish before we start another.
  6. thread.wait_to_finish()
  7. thread = Thread.new()
  8. print("START THREAD!")
  9. # Our method needs an argument, so we pass it using bind().
  10. thread.start(_bg_load.bind("res://mona.png"))
  11. func _bg_load(path: String):
  12. print("THREAD FUNC!")
  13. var tex = load(path)
  14. # call_deferred() tells the main thread to call a method during idle time.
  15. # Our method operates on nodes currently in the tree, so it isn't safe to
  16. # call directly from another thread.
  17. _bg_load_done.call_deferred()
  18. return tex
  19. func _bg_load_done():
  20. # Wait for the thread to complete, and get the returned value.
  21. var tex = thread.wait_to_finish()
  22. print("THREAD FINISHED!")
  23. $TextureRect.texture = tex
  24. # We're done with the thread now, so we can free it.
  25. thread = null # Threads are reference counted, so this is how we free them.
  26. func _exit_tree():
  27. # You should always wait for a thread to finish before letting it get freed!
  28. # It might not clean up correctly if you don't.
  29. if is_instance_valid(thread) and thread.is_started():
  30. thread.wait_to_finish()
  31. thread = null