[swift-evolution] [pitch] Atomics

Joe Groff jgroff at apple.com
Fri Feb 24 15:11:07 CST 2017


> On Feb 23, 2017, at 1:44 PM, Guillaume Lessard via swift-evolution <swift-evolution at swift.org> wrote:
> 
> There is no clean way to use atomic operations in Swift at the moment, even less so after most of OSAtomic.h was deprecated in Sierra. Of course, the OSAtomic calls were never available in Linux, so there are no atomics at all on that side. It's technically possible to wrap clang’s C11 atomics for use in Swift; such a wrapper can be made cross-platform, but still isn't a particularly great solution.
> 
> It looks to me as if this would pretty much be a library addition, since atomics support seems to be fairly complete in the Builtin module. Would a proposal be welcome?
> 
> I sketched an atomic Int64 in the following branch:
> https://github.com/glessard/swift/tree/atomics-sketch

This implementation approach won't work. If you're `mutating` or `inout`-ing something, that implies you have exclusive access to the memory being mutated, which is at odds with the very nature of atomics. The only way you can make atomics sort-of-work in Swift today is by performing atomic operations on manually-allocated memory, since Swift doesn't provide the necessary control over any memory the language manages to get the guarantees you need. When we get the ownership model, you could then model atomics as *shared* borrowed values (as opposed to the *exclusive* borrowing required by `inout` today); today, the best we could hope to offer is something akin to the OSAtomic interface offering atomic operations on raw memory, but I don't think that's a very good interface, or one we want to be stuck supporting forever.

-Joe


More information about the swift-evolution mailing list