tags:

views:

90

answers:

1

For the functions here:

#include <libkern/OSAtomic.h>

there are OSAtomic and OSAtomicBarrier versions.

However, the documentation does not show sample code for:

  1. When is it safe to use just OSAtomic, without the OSAtomicBarrier version
  2. When is it that OSAtomic would be unsafe, but OSAtomiBarrier would be safe.

Can anyone provide explainations + sample codes?

[Random ramblings of "your opinion" without actual code is useless. Readers: please down vote such answers; and vigrously upvote answers with actual code.]

[C/C++ code preferred; Assembly okay too.]

+1  A: 

On Intel and uniprocessor platforms, it doesn't matter.

For multiprocessor PPC systems, you should always use the barrier variety of functions, unless the atomic store affects no data other than the atomic variable.

The following would not be ok:

data_structure[y].data++;
OSAtomicIncrement32(y);

You must use a barrier here, because other threads may see data_structure as out of date.

However, if you are using an atomic variable for some purpose where it stands alone, you may omit the barrier:

// y is not used to access any other data
OSAtomicIncrement32(y);

Fine, as long as the value of y does not affect the variable of any shared data structure.

Essentially, it's a cache flush. You can always safely use the barrier functions, but in some cases, you may be able to improve performance by not using the barrier functions, such as if y is not used relative to a data structure. There are probably not many cases where you can use the functions without the barrier.

WhirlWind
Why does it not matter on Intel multiprocessor systems?
anon
This explains it at a high level better than I can:http://www.linuxjournal.com/article/8211
WhirlWind