How to use threads with parameters in Godot 4.0?
Asked Answered
S

3

0

I have an issue with threads with parameters in Godot 4.0
I’m looking for an example of how to use thread.start() with Godot 4.0
My func looks like this:

func _ready():
	thread = Thread.new()
	thread.start("setname",[tim,bob,lea])

func setname(new):
	for i in range(0,new.size()):
		print(new[i])

I can get a basic thread to run but as soon as I add any parameters for the function it refuses to run. I'm not sure what I'm doing wrong.

Seisin answered 29/9, 2022 at 6:8 Comment(0)
S
0

This is the answer I was looking for:

thread.start(setname.bind([tim,bob,lea])

You no longer use "" with the function name and add .bind(+parameters).

Seisin answered 29/9, 2022 at 9:55 Comment(0)
S
0

Welcome :-)

Well, 'For' with a capital letter is a typo. 'thread' must be declared with 'var' either in the script header or locally in the function _ready(). I also don't see a definition of tim, bob and lea.

And I would advise to actually annotate the thread-function parameter with a type to make clear to the reader what it expects as a parameter. I would also give things meaningful names. like 'var name_thread = Thread.new()', and 'func setname( new_name: Array):'. The type annotation is technically not necessary, but makes reading easier.

See the documentation for how to start a thread, because your version uses the wrong syntax:
https://docs.godotengine.org/en/latest/tutorials/performance/using_multiple_threads.html

Threads are advanced concepts and one can easily mess up things. For instance not waiting for a thread to finish in the context in which it is valid is a grave mistake.

Skewbald answered 29/9, 2022 at 7:43 Comment(0)
S
0

This is the answer I was looking for:

thread.start(setname.bind([tim,bob,lea])

You no longer use "" with the function name and add .bind(+parameters).

Seisin answered 29/9, 2022 at 9:55 Comment(0)
S
0

Skewbald Thanks, the typo was just on this post not in my code. thanks for pointing it out and the extra info.

Seisin answered 29/9, 2022 at 9:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.