OSAtomic vs. C++11 atomic
OSAtomic vs. C++11 atomic
- Subject: OSAtomic vs. C++11 atomic
- From: "Stephen F. Booth" <email@hidden>
- Date: Mon, 28 Oct 2013 15:21:09 -0400
In the past I’ve used OSAtomicTestAndSet() and OSAtomicTestAndClear() as a method of communicating flag values across threads. C++11’s <atomic> header introduces native atomic operations into the STL. So existing code looking like:
uint32_t flags = 0;
// In thread A
OSAtomicTestAndSet(kFlagValue, &flags);
// In thread B
if(flags & kFlagValue) {
OSAtomicTestAndClear(kFlagValue, &flags);
// Do something based on kFlagValue
}
can be rewritten using C++11 as
std::atomic_uint flags = 0;
// In thread A
flags.fetch_or(kFlagValue);
// In thread B
if(kFlagValue & flags.load()) {
flags.fetch_and(~kFlagValue);
// Do something based on kFlagValue
}
In my experiments I haven’t noticed a difference in functionality or speed. The C++11 methods call through to clang builtin functions like _c11_atomic_fetch_or, and I’m wondering whether the clang builtins use OSAtomic under the hood or some other method of ensuring atomicity? Also, the C++11 atomic classes have six options for memory ordering which seem like they could speed things up. Is there an advantage to using one method over the other in C++?
Stephen
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden