Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

WorkerThreadPool

Inherits: Object

A singleton that allocates some Threads on startup, used to offload tasks to these threads.

Description

The WorkerThreadPool singleton allocates a set of Threads (called worker threads) on project startup and provides methods for offloading tasks to them. This can be used for simple multithreading without having to create Threads.

Tasks hold the Callable to be run by the threads. WorkerThreadPool can be used to create regular tasks, which will be taken by one worker thread, or group tasks, which can be distributed between multiple worker threads. Group tasks execute the Callable multiple times, which makes them useful for iterating over a lot of elements, such as the enemies in an arena.

Here's a sample on how to offload an expensive function to worker threads:

var enemies = [] # An array to be filled with enemies.

func process_enemy_ai(enemy_index):
    var processed_enemy = enemies[enemy_index]
    # Expensive logic...

func _process(delta):
    var task_id = WorkerThreadPool.add_group_task(process_enemy_ai, enemies.size())
    # Other code...
    WorkerThreadPool.wait_for_group_task_completion(task_id)
    # Other code that depends on the enemy AI already being processed.

The above code relies on the number of elements in the enemies array remaining constant during the multithreaded part.

Note: Using this singleton could affect performance negatively if the task being distributed between threads is not computationally expensive.

Tutorials

Methods

int

add_group_task ( Callable action, int elements, int tasks_needed=-1, bool high_priority=false, String description="" )

int

add_task ( Callable action, bool high_priority=false, String description="" )

int

get_group_processed_element_count ( int group_id ) const

bool

is_group_task_completed ( int group_id ) const

bool

is_task_completed ( int task_id ) const

void

wait_for_group_task_completion ( int group_id )

Error

wait_for_task_completion ( int task_id )


Method Descriptions

int add_group_task ( Callable action, int elements, int tasks_needed=-1, bool high_priority=false, String description="" )

Adds action as a group task to be executed by the worker threads. The Callable will be called a number of times based on elements, with the first thread calling it with the value 0 as a parameter, and each consecutive execution incrementing th