Unreal - Memory order issues when TSharedPtr implements reference counting

Here we use the following code as an example for analysis. It may change in later versions of Unreal but will be similar.

FORCEINLINE void AddSharedReference()
{
    SharedReferenceCount.FetchAdd(1, EMemoryOrder::Relaxed);
}

void ReleaseSharedReference()
{
    RefCounter::ValueType OldSharedReferenceCount = SharedReferenceCount.FetchSub(1, EMemoryOrder::Release);

    if (OldSharedReferenceCount == 1)
    {
        AtomicThreadFence(EMemoryOrder::Acquire);

        DestroyObject();

        ReleaseWeakReference();
    }
}

This code has three behaviors involving memory order, namely increasing the reference count, decrementing the reference count, and destroying the managed object.

In newer Unreal Engine implementations, the latter two behaviors involving memory order are merged.

Increment reference count

Since the managed object must be in a valid state before and after the reference count is incremented, there is no memory order requirement.

Decrement reference count

In a multi-threaded environment, even if the reference count is not 1 before the reference count is decremented, it may be decremented to 0 by other threads immediately afterwards. When the reference count is 0, it means that the managed object enters an invalid state and can be destroyed on any thread. Therefore, we need to ensure that all operations on managed objects will not be reordered after the decrement operation to avoid operating invalid objects.

In summary, we need to use freed Memory order to indicate that reads or writes in the current thread cannot be reordered after this store, and all writes by the current thread are visible to other threads that acquire the same atomic variable, that is, the thread that executes the operation of destroying the managed object.

Destroying a managed object

In a multi-threaded environment, when the current thread destroys a managed object, other threads may have just operated on the managed object, and their operations have not been fully synchronized to the current thread. If the managed object is destroyed directly at this time, data competition may lead to undefined behavior.

In summary, we need to use obtain Memory ordering to indicate that reads or writes in the current thread cannot be reordered before this load. All writes by other threads that release the same atomic variable are visible to the current thread. The other threads are the threads that just operated on the managed object.

From the above analysis, we can see that the typical Release acquisition order .

Post Reply