thread.gd 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. extends Control
  2. var thread: Thread
  3. func _on_load_pressed() -> void:
  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_rich("[b]Starting 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) -> Texture2D:
  12. print("Calling thread function.")
  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() -> void:
  20. # Wait for the thread to complete, and get the returned value.
  21. var tex: Texture2D = thread.wait_to_finish()
  22. print_rich("[b][i]Thread finished.\n")
  23. $TextureRect.texture = tex
  24. # We're done with the thread now, so we can free it.
  25. # Threads are reference counted, so this is how we free them.
  26. thread = null
  27. func _exit_tree() -> void:
  28. # You should always wait for a thread to finish before letting it get freed!
  29. # It might not clean up correctly if you don't.
  30. if is_instance_valid(thread) and thread.is_started():
  31. thread.wait_to_finish()
  32. thread = null