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以来,我一直在运行原子和可选的更改日志,但是我发现没有什么能真正解释这种行为。
有什么想法吗?
发布于 2015-05-28 08:07:13
比如std::atomic, requires trivially copyable types。boost::optional并不是微不足道的可复制的,所以您只是得到了未定义的行为。
顺便说一句,compare_exchange_*像用memcmp比较对象,所以它也会考虑任何填充字节。
https://stackoverflow.com/questions/30500378
复制相似问题