Question

Anyone know what gcc does with expressions passed as the value for atomic builtins. Consider the function below. Will gcc guarantee the atomicity of this operation? (even though extra cycles are required to compute 2 << nr?

static inline test_and_set_bit(volatile void *addr, int nr, int set) {
    __sync_fetch_and_or(addr, set ? 2 << nr : 0);
}

Thanks!

Was it helpful?

Solution

The expression set ? 2 << nr : 0 must be evaluated before the __sync_fetch_and_or() operation is initiated. So the fetch-and-or access to addr will be atomic - no problem.

Just to be clear - the read/modify/write actions to the memory pointed to by addr will occur atomically - the evaluation of the value to be or'ed in will not be atomic (but it doesn't need to be).

OTHER TIPS

Your function will be equivalent to this function (they will probably even compile to the exact same code):

static inline test_and_set_bit(volatile void *addr, int nr, int set) {
    const int bit = set ? 2 << nr : 0;
    __sync_fetch_and_or(addr, bit);
}

The expression will not be evaulated 'atomically', but since it involves all local variables that's not relevant. The __sync_fetch_and_or will be executed atomically. You might want to change your function to look like this one so that people coming after you will not be confused.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top