GetAndSet function (corresponding to cas function)

Andrew Wiley wiley.andrew.j at gmail.com
Mon Dec 26 15:39:21 PST 2011


On Mon, Dec 26, 2011 at 4:05 PM, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> On Monday, December 26, 2011 20:34:39 Adrian Mercieca wrote:
>> Hi folks,
>>
>> Would anyone answer me on this please?
>>
>> To clarify, in Java there is are getAndSet methods on Atomic type objects
>> (along with compareAndSet).
>>
>> I know that in D there is the cas function (equivalent to Java's
>> compareAndSet); is there an equivalent D function for Java's getAndSet
>> please?
>
> If it's not in core.atomic, then probably not. It has atomicLoad and
> atomicStore, but I don't see anything that tries to combine the two, assuming
> that that's what you want be getAndSet.

getAndSet can easily be implemented as a utility method using cas and
atomicLoad. It's not a primitive atomic operation, it's just a
convenience function.

T getAndSet(T)(shared(T)* location, T newValue) {
    while(1) {
        auto current = atomicLoad(*location);
        if(cas(location, current, newValue))
            return current;
    }
}

Someone who knows more about the options to atomicLoad could probably
make this faster, but because we're using cas, it's guaranteed to be
correct.


More information about the Digitalmars-d-learn mailing list