How to use mutex in Unreal Engine

Unreal Engine has an alternative implementation of std::mutex called FCriticalSection which makes it possible for your data to be safely accessed from different threads, preventing race conditions. This takes the same approach, handling it with one thread locking until the other thread completes the necessary operations. There are two ways to handle lock/unlock logic. The first is low-level, which is used to directly lock and unlock threads. Use with caution due to possible deadlocks ....

December 21, 2022 · 2 min · Georgy Treshchev

How to properly work with UObjects in background threads (GC)

This article addresses the question of how to work with UObjects in a thread-safe way when dealing with workers, async tasks, thread pools, or whatever else using a non-game thread. One critical issue to address is the handling of garbage collection. When passing an UObject, which is not set to root, directly to a background thread, there’s a risk that the garbage collector may silently delete the passed UObject. Even frequent validity checks of the UObject (e....

November 30, 2022 · 4 min · Georgy Treshchev

How to use async task in Unreal Engine

Unreal Engine has a useful feature called AsyncTask that allows you to execute code asynchronously. It functions by running specific code on a specified thread and is primarily used when the task is too heavy to be executed instantly without blocking the game thread. It also provides a solution to issues arising from multithreading, particularly accessing properties from one thread that are intended to be used and/or modified in another thread....

July 31, 2022 · 2 min · Georgy Treshchev

How to create a multi-threaded for loop in Unreal Engine

Unreal Engine has different approaches to parallelize your code and one of them is ParallelFor. It is used when it is necessary to execute code multiple times with different number-based inputs, basically what a regular for loop does. But unlike a regular for loop that executes sequentially, ParallelFor runs on different threads, with possible different order of execution. Let’s say our task is to simply sum the values from the TArray<int32> array....

July 23, 2022 · 2 min · Georgy Treshchev