大于比较和交换 [英] Greater-than compare-and-swap

查看:69
本文介绍了大于比较和交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的,我正在寻找一个比较交换方案,但具有大于比较的结果:

As the title suggests, I'm looking for a compare-and-swap implementation, but with greater-than comparison:

if(newValue > oldValue) {
    oldValue = newValue;
}

其中oldValue是某些全局共享状态,而newValue是每个线程专用的,而无需执行以下操作:

where oldValue is some global shared state and newValue is private to each thread, without doing this:

synchronized(locker) {
    if(newValue > oldValue) {
        oldValue = newValue;
    }       
}

因为我想要一个非阻塞的解决方案.通过研究其他非阻塞操作的源代码,我想到了这一点(假设值是整数):

because I want a non-blocking solution. From studying source codes of other non-blocking operations, I've come up with this (assuming the values are integers):

AtomicInteger oldValue; // shared global variable

...

public boolean GreaterThanCAS(int newValue) {

    while(true) {
        int local = oldValue;
        if(local == oldValue) {
            if(newValue > local) {
                 if(oldValue.compareAndSet(local, newValue) {
                     return true;  // swap successful
                 } // else keep looping
            } else {
                 return false; // swap failed
            }
        } // else keep looping
    }
}

// else keep looping发生时,这意味着同时有另一个线程更改了oldValue,因此我需要循环并重试.

when // else keep looping happens, it means that another thread has changed the oldValue in the meantime and so I need to loop and try again.

此实现是否正确(线程安全)?

Is this implementation correct (thread-safe)?

推荐答案

我发现您的实现没有问题,假设没有线程会降低AtomicInteger 的值.如果是这样,您的代码就可以接受竞争条件.

I see no problems with your implementation, provided that no thread ever decreases the value of the AtomicInteger. If they do, your code is open to race conditions.

请注意,代码可以简化如下:

Note that the code can be simplified as follows:

public boolean GreaterThanCAS(int newValue) {
    while(true) {
        int local = oldValue.get();
        if(newValue <= local) {
             return false; // swap failed
        }
        if(oldValue.compareAndSet(local, newValue)) {
             return true;  // swap successful
        }
        // keep trying
    }
}

这篇关于大于比较和交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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