For the functions here:
#include <libkern/OSAtomic.h>
there are OSAtomic and OSAtomicBarrier versions.
However, the documentation does not show sample code for:
OSAtomic
, without the OSAtomicBarrier
versionOSAtomic
would be unsafe, but OSAtomicBarrier
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.]
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.
I think this article a more detailed explain of what's going here: http://www.mikeash.com/pyblog/friday-qa-2011-03-04-a-tour-of-osatomic.html. Pretty good read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With