MacOSX: OSAtomic vs OSAtomicBarrier
For the functions here:
#include <libkern/OSAtomic.h>
there are OSAtomic and OSAtomicBarrier versions.
However, the documentation does not show sample code for:
- When is it safe to use just
OSAtomic
, without theOSAtomicBarrier
version - When is it that
OSAtomic
would be unsafe, butOSAtomicBarrier
would be safe.
Ca开发者_StackOverflow社区n 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.
精彩评论