Re: OSAtomic vs. C++11 atomic
Re: OSAtomic vs. C++11 atomic
- Subject: Re: OSAtomic vs. C++11 atomic
- From: Howard Hinnant <email@hidden>
- Date: Mon, 28 Oct 2013 15:44:28 -0400
On Oct 28, 2013, at 3:21 PM, "Stephen F. Booth" <email@hidden> wrote:
> 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?
The clang builtins are implemented in the compiler whenever possible, and otherwise farmed out to a low level library called compiler_rt. Things are only farmed out when the intrinsic needs a mutex to get the job done (which won't happen with fundamental types like unsigned).
> 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++?
There can be. But this is a most dangerous tool to play with. I highly recommend using the default memory ordering unless absolutely forced by performance testing to explore relaxing the memory ordering to a bare minimum. The bare minimum will depend upon your use case, and will require most experts 3 tries each to get it right. Here be dragons.
Howard
_______________________________________________
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