我正在学习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;
}
为什么要先加载?
因为
.load(std::memory_order_relaxed)
快而 .compare_exchange_strong(Expected, 1u)
慢。