понедельник, 19 декабря 2011 г.

OpenCL 1.1: Atomic operations on floating point values

Atomic operations on floating point values in OpenCL standard is not exist (except atomic_xchg), but we can implement it using atomic_cmpxchg:
inline void AtomicAdd(volatile __global float *source, const float operand) {
    union {
        unsigned int intVal;
        float floatVal;
    } newVal;
    union {
        unsigned int intVal;
        float floatVal;
    } prevVal;
    do {
        prevVal.floatVal = *source;
        newVal.floatVal = prevVal.floatVal + operand;
    } while (atomic_cmpxchg((volatile __global unsigned int *)source, prevVal.intVal, newVal.intVal) != prevVal.intVal);
}
 We also can implement AtomicAddLocal function by using  "volatile __local" instead of "volatile __global".

Other operations:
AtomicMul(): newVal.floatVal = prevVal.floatVal * operand;
AtomicMad(source,operand1,operand2): newVal.floatVal = mad(operand1,operand2,prevVal.floatVal);
AtomicDiv(): newVal.floatVal = prevVal.floatVal / operand;

              ...