开发者

Atomic increment on mac OS X

I have googled for atomic increment and decrement operators on Mac OS X and found "OSAtomic.h", but it seems you can only use this in kernel开发者_Go百科 space.

Jeremy Friesner pointed me at a cross-platform atomic counter in which they use assembly or mutex on OS X (as far as I understood the interleaving of ifdefs).

Isn't there something like InterlockedDecrement or atomic_dec() on OS X ?


What makes you think OSAtomic is kernel space only? The following compiles and works fine.

#include <libkern/OSAtomic.h>
#include <stdio.h>

int main(int argc, char** argv) {
  int32_t foo = 1;
  OSAtomicDecrement32(&foo);
  printf("%d\n", foo);

  return 0;
}


Currently, the recommendation is to use C++11's std::atomic.


You could also check out Intel's Threaded Building Blocks for their atomic template class.


You can also use IncrementAtomic() and DecrementAtomic() via CoreServices:

#include <CoreServices/CoreServices.h>

int main(int argc, char** argv) 
{
  int val = 0;
  IncrementAtomic(&val);
  DecrementAtomic(&val);    

  return 0;
}

Note: the return value of these functions is the value of the integer before it is incremented, so if you want similar behavior to the Win32 InterlockedIncrement() and InterlockedDecrement() functions, you will need to create wrappers that +1 to the return value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜