struct Foo
{
void updateMin(const int& value);
boost::atomic<boost::optional<int>> m_min; //multi-thread access
};
void Foo::updateMin(const int& value)
{
auto currentMin = m_min.load(boost::memory_order_relaxed);
int newMin;
do
{
if (!currentMin)
newMin = value;
else
{
newMin = std::min(value, currentMin.get());
if (newMin == currentMin)
break;
}
} while (!m_min.compare_exchange_weak(currentMin, boost::optional<int>(newMin), boost::memory_order_relaxed));
}
在 boost 1.55 中,上述代码按预期工作。
当我尝试将 boost 版本更新到 1.58 时,compare_exchange_weak 系统地失败并因此导致无限循环。
自 1.55 以来,我查看了 atomic 和 optional 的更改日志,但我发现没有任何明显的东西可以解释这种行为。
有什么想法吗?
最佳答案
像 std::atomic
, boost::atomic
requires trivially copyable types .
boost::optional
不可简单复制,因此您只会得到未定义的行为。
顺便说一下,compare_exchange_*
比较对象就像通过 memcmp
一样,因此它也会考虑任何填充字节。
关于c++ - boost::atomic 与 boost::optional 不同的行为与 boost 1.55 和 1.58,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30500378/