boost :: atomic with boost ::使用boost 1.55和1.58可选的不同行为

Gui*_*e07 1 c++ boost atomic

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));
}
Run Code Online (Sandbox Code Playgroud)

使用boost 1.55,上面的代码按预期工作.

当我尝试将boost版本更新为1.58时,compare_exchange_weak会系统地失败,从而导致无限循环.

从1.55开始,我已经安装了原子和可选的更改日志,但我发现解释这种行为并不是很明显.

有任何想法吗 ?

T.C*_*.C. 5

喜欢std::atomic,boost::atomic需要简单的可复制类型. boost::optional不是简单的可复制,所以你只是得到未定义的行为.

顺便说一句,compare_exchange_*比较对象memcmp就好了,所以它也会考虑任何填充字节.