CompareAndExchange On三个原子变量 [英] CompareAndExchange On Three atomic variable

查看:490
本文介绍了CompareAndExchange On三个原子变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要比较和交换3个原子变量:

I want to compare and exchange 3 atomic variable:

std::atomic<int> a;
std::atomic<int> expected;
std::atomic<int> new;

int expectedValue = std::atomic_load_explicit(&expected, std::memory_order_relaxed);
int newValue = std::atomic_load_explicit(&new, std::memory_order_relaxed);

std::atomic_compare_exchange_strong_explicit(
    &a, 
    &expectedValue, 
    newValue, 
    std::memory_order_relaxed, 
    std::memory_order_relaxed);

但是如果在读取预期 code> new 变量并将它们与 a 进行比较,另一个线程更改它们的值,当前线程将按照以前的值工作,更改代码到它:

But if in between reading expected and new variables and comparing them to a, one another thread change theirs values, current thread will work by previous values, so i change code to it:

while(true)
{
    int expectedValue = std::atomic_load_explicit(&expected, std::memory_order_relaxed);
    int newValue = std::atomic_load_explicit(&new, std::memory_order_relaxed);

    std::atomic_compare_exchange_strong_explicit(
        &a, 
        &expectedValue, 
        newValue, 
        std::memory_order_relaxed, 
        std::memory_order_relaxed);

    int newExpectedValue = std::atomic_load_explicit(&expected, std::memory_order_relaxed);
    int newNewValue = std::atomic_load_explicit(&new, std::memory_order_relaxed);

    if(newExpectedValue == expectedValue && newNewValue == newValue)
        break;
}

我的代码是否正确?

推荐答案

您重写的函数仍然可能给出不一致的结果。加载到 newExpectedValue 后,但在检查 newExpectedValue = 之前,如果 = expectedValue ?如果在加载预期后更改 new 但在之前?

Your rewritten function can still give inconsistent results. What if expected changes after you load it into newExpectedValue, but before you check if newExpectedValue == expectedValue? What if new and expected change after you load expected, but before new?

这不是如何使用原子。如果您需要以原子方式执行涉及三个变量的操作,则应在操作期间使用锁定来序列化访问。互斥锁或自旋锁在这里更合适。

This isn't how atomics are intended to be used. If you need to do an operation involving three variables atomically, you should be using a lock to serialize access during the operation. A mutex or spin lock would be more appropriate here.

这篇关于CompareAndExchange On三个原子变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆