Swift Atomics Library
Article Summary
Karoy Lorentey from Apple just dropped Swift Atomics, bringing C/C++ style low-level atomic operations directly into Swift. This changes the game for systems programmers who've been blocked from building concurrent data structures in pure Swift.
Apple's Swift team released an open source package enabling atomic operations in Swift code, based on the recently accepted SE-0282 proposal. The library provides the foundation for building synchronization constructs and concurrent data structures without resorting to other languages.
Key Takeaways
- Supports atomic operations on integers, booleans, pointers, and class references
- Two wrappers: ManagedAtomic (memory safe) and UnsafeAtomic (flexible, manual management)
- All operations guaranteed lock-free, mapping to dedicated CPU instructions where available
- Atomic strong references enable memory reclamation fitting Swift's reference counting model
- Use sparingly: isolate to small units and apply Thread Sanitizer liberally
Swift developers can now build concurrent data structures in pure Swift using carefully designed atomic APIs that were previously only accessible through C/C++.
About This Article
Swift programmers couldn't access low-level atomic operations needed to build synchronization constructs. They had to import implementations from C/C++ instead of writing concurrent data structures directly in Swift.
Karoy Lorentey's team built the Atomics package with atomic storage representations kept separate from regular types. It provides ManagedAtomic and UnsafeAtomic wrappers that map to C/C++ standard memory_order semantics, leaving out the discouraged memory_order_consume.
Systems programmers can now build lock-free concurrent data structures entirely in Swift. Atomic strong references use DoubleWord operations for efficient memory reclamation that works well with Swift's reference counting model.