Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MacOSX: OSAtomic vs OSAtomicBarrier

Tags:

macos

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 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.]

like image 925
anon Avatar asked Mar 12 '10 23:03

anon


2 Answers

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.

like image 82
WhirlWind Avatar answered Oct 18 '22 20:10

WhirlWind


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.

like image 33
jaysqrd Avatar answered Oct 18 '22 18:10

jaysqrd