[swift-users] Atomics and Memory Fences in Swift

Anders Ha hello at andersio.co
Sun Dec 4 21:52:31 CST 2016

> On 5 Dec 2016, at 1:53 AM, Andrew Trick <atrick at apple.com> wrote:
>> On Nov 30, 2016, at 5:40 AM, Anders Ha via swift-users <swift-users at swift.org <mailto:swift-users at swift.org>> wrote:
>> Hi guys
>> I have recently started adopting lock-free atomics with memory fences, but it seems Swift at this moment does not have any native instruments.
>> Then I read a thread in the Apple Developer Forum (https://forums.developer.apple.com/thread/49334 <https://forums.developer.apple.com/thread/49334>), which an Apple staff claimed that all imported atomic operations are "not guaranteed to be atomic". But for my tests with all optimizations enabled (-Owholemodule and -O), the OSAtomic primitives and stdatomic fences do not seem going wild.
>> Is these `atomic_*` and `OSAtomic*` primitives really unsafe in Swift as claimed? It doesn't seem like the Swift compiler would reorder memory accesses around a C function call that it wouldn't be able to see through.
> Did you get an answer to this? I’m not sure what led you to believe the primitives are unsafe in Swift. Importing them doesn’t change their semantics.
> -Andy

I wrote to ask because I have stumbled on the posts (which I linked) of a colleague of yours working on Core Audio, with the specific quote of "even using functions imported from C is not guaranteed to be atomic". To some extent I believe it is true, since the Swift compiler does not define a memory model to say it doesn't reorder stuff in this or that situation.

But it doesn't seem to be a problem in practice, as stuff apparently isn't being reordered around the function calls in generated code. So I guess the answer is "Swift does not have a memory model and you are relying on a unconstrained aspects of the compiler not to fail you". Hmm?


>> P.S. Is any of these primitives available on Linux? It seems the glibc modulemap does not export an `stdatomic` submodule at all.
>> Best Regards,
>> Anders
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org <mailto:swift-users at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-users <https://lists.swift.org/mailman/listinfo/swift-users>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20161205/b023a8aa/attachment.html>

More information about the swift-users mailing list