Background
Sometimes you may suddenly find the game has entered a frozen state, or a task on some thread has not completed for a long time. In this case, you need to consider whether the thread is stuck, for example due to resource contention, an infinite loop, etc. Usually, we can introduce a monitoring thread that uses a heartbeat mechanism to determine whether a thread is still alive. If a thread has not reported a heartbeat for a period of time, it can be considered stuck; at that point you can dump the stack or directly have the program trigger an assert.
Mechanism Overview
Unreal Engine has an FThreadHeartBeat class that maintains the thread heartbeat mechanism.
Main thread heartbeat: GameThreadHitchHeartBeat.
Throughout the engine code, calls to FThreadHeartBeat::Get().HeartBeat() are already handled; in some places where detection is not needed, detection is also suspended.
Core Idea
The mechanism creates an FThreadHeartBeat thread that periodically checks the last heartbeat time of other participating threads; if it times out, it performs operations such as outputting logs.
It also needs to record the time of the last hang (Hang) to avoid repeated detection reports.
If you need to obtain the target thread’s stack, you can use FPlatformStackWalk::CaptureThreadStackBackTrace to get the current stack of the specified thread.
Specifically, for render detection, it directly performs a Crash.
How to Use
Enabling the Configuration
The core feature only requires configuring the corresponding detection time in DefaultEngine.ini to detect deadlocks on the main thread:
| |
Note that the default macro control is:
| |
That is, it is not enabled in the Editor environment. If you want to test it, you can remove && !WITH_EDITORONLY_DATA and recompile.
Custom Threads
If you need to detect other threads, just call FThreadHeartBeat::HeartBeat() in the Tick of the corresponding thread so that the heartbeat thread records it.
Long-Running Tasks
Sometimes we need to explicitly execute a task for a long time. In this case, you can use the FSlowHeartBeatScope class to construct a lock, letting the detection thread know that the current period explicitly does not need detection.
Its principle is: in the constructor, call FThreadHeartBeat::SuspendHeartBeat to mark SuspendedCount++, and in the destructor, call FThreadHeartBeat::ResumeHeartBeat to mark --SuspendedCount.
During detection, only threads with SuspendedCount == 0 are processed.