是否需要在compare_exchange_strong()之前调用load()?

问题描述 投票:0回答:1

我正在学习C++内存序列,我在Unreal Engine5中找到了这段代码。我的问题是为什么不直接调用

compare_exchange_strong()
而不是先调用
load()

FHttpRequest* GetFreeRequest()
{
    for (uint8 i = 0; i < Pool.Num(); ++i)
    {
    if (!Pool[i].Usage.load(std::memory_order_relaxed)) //<-why load first?
    {
        uint8 Expected = 0u;
        if (Pool[i].Usage.compare_exchange_strong(Expected, 1u))
        {
            Pool[i].Request->Reset();
            return Pool[i].Request;
        }
    }
    }
    return nullptr;
}

我认为删除

load()
调用并将其更改为这样的内容是可以的:

FHttpRequest* GetFreeRequest()
{
    for (uint8 i = 0; i < Pool.Num(); ++i)
    {
    uint8 Expected = 0u;
        if (Pool[i].Usage.compare_exchange_strong(Expected, 1u))
    {
            Pool[i].Request->Reset();
        return Pool[i].Request;
    }
    }
    return nullptr;
}
c++ memory-barriers
1个回答
0
投票

为什么要先加载?

因为

.load(std::memory_order_relaxed)
快而
.compare_exchange_strong(Expected, 1u)
慢。

© www.soinside.com 2019 - 2024. All rights reserved.