Why do C++11 CAS operations take two pointer parameters?

谁都会走 提交于 2019-12-03 23:49:17

The C++11 way is more useful: If the exchange fails, then *expected is updated to the new, current value. That makes it easy to use the function in a loop:

T value = x.load();
T newvalue = frob(value);

while (!atomic_compare_exchange(&x, &value, newvalue))
{
    newvalue = frob(value);
}

With the Microsoft signature, testing whether the operation succeeded is more cumbersome, and ditto for GCC's __sync_type version. With GCC's __sync_bool, you even need to perform another load each time the exchange fails.

I don't see why you wouldn't have both though. In my use-case the C++ version is less useful. I want to wait until a variable has some value then I want to set it to a new value.

With GCC instrinsics:

while (!__sync_bool_compare_and_swap(&value, expected, desired)) { }

With C++11:

auto tmp = expected;
while (!value.compare_exchange_weak(tmp,desired)) 
{
  tmp = expected;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!