Compare and Swap

You can use the Machine Interface's (MI) Compare and Swap (CMPSWP) instruction to access data in a multithreaded program.

CMPSWP compares the value of a first compare operand to the value of a second compare operand. If they are equal, the swap operand is stored in the second compare operand's location. If they are unequal, the second compare operand is stored into the first compare operand's location.

When an equal comparison occurs, it is assured that no access by another CMPSWP instruction will occur at the second compare operand location between the moment that the second compare operand is fetched for comparison and the moment that the swap operand is stored at the second compare operand location.

When an unequal comparison occurs, no atomicity guarantees are made regarding the store to the first compare operand location and other CMPSWP instruction access. Thus only the second compare operand should be a variable shared for concurrent processing control.

The following code example for a C macro can be used to atomically increment or decrement an integer variable.

#ifndef __cmpswp_h
    #include <mih/cmpswp.h>
#endif

#define ATOMICADD ( var, val, rc ) { \
    int aatemp1 = (var); \
    int aatemp2  = aatemp1 + val; \  
    while( ! _CMPSWP( &aatemp1, &var, aatemp2 ) ) \
       aatemp2 = aatemp1 + val; \
    rc = aatemp2; \
}

In the code example, var is an integer to be incremented or decremented, val is an integer value to be added or subtracted from var, and rc is the resultant value.