How do I pass parameters to a thread using WorkerThreadPool?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MEDBVLL

In Godot 4, callables were introduced to the engine, however, I can’t find any way of passing arguments to a Callable when calling WorkerThreadPool.add_task(Callable action, bool high_priority=false, String description="") how do I do it?

Currently you don’t using add_task. However, add_group_task can take a number of elements and the callable receives an index, which is handy for working with an array (for example). Sharing data with workers should use queues and synchronisation primitives ideally.

spaceyjase | 2023-06-02 22:06

On writing that, I forgot about bind:

var callable = Callable(self, “worker_with_args”).bind(arg)
WorkerThreadPool.add_task(callable)

Does that work?

spaceyjase | 2023-06-02 22:19

:bust_in_silhouette: Reply From: spaceyjase

I tried this, it works fine. bind returns a copy of the Callable with (one or more) args bound to it. The example prints ‘1’:

func _ready() -> void:
    var callable = Callable(self, "worker_with_args").bind(1)
    WorkerThreadPool.add_task(callable)


func worker_with_args(arg: int) -> void:
    print(arg)