logo
vision scalability social networking revelation source

Write your own InterlockedXxx operation

It has long been known that InterlockedCompareExchange can be used to write any Interlockedxxx operation.

long InterlockedXxx(
        __inout long  volatile *Target,
        , whatever parameters we need for Xxx
        )
    {
        long prevValue, prevCopy;

        prevValue = *Target;

        do {
            if Xxx operations is illegal on prevValue, return with error code

            prevCopy = prevValue;

            //
            // prevValue will be the value that used to be Target if the exchange was made
            // or its current value if the exchange was not made.
            //
            prevValue = InterlockedCompareExchange(Target, Xxx operation on prevCopy, prevValue);

            //
            // If prevCopy == prevValue, then no one updated Target in between the deref at the top
            // and the InterlockecCompareExchange afterward and we are done
            //
        } while (prevCopy != prevValue);

        //
        // [value] can be anything you want, but it is typically either
        // a) The new value stored in Target.  This is the type of return value that
        //    InterlockedIncrement returns
        // or
        // b) The new value is the previous value that was in Target.  This si the
        //     type of return value that InterlockedOr or InterlockedExchange return
        //
        return [value];
    }

Structures larger than a long can be handled by using InterlockedCompareExchange to add to a linked list, or remove stuff from a linked list. Of course you should not be writing such things yourself, when Intel has already written it for you.

Creative Commons License reaction.la gpg key 154588427F2709CD9D7146B01C99BB982002C39F
This work is licensed under the Creative Commons Attribution 4.0 International License.