Swift.org Blog Karoy Lorentey Oct 1, 2020

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

Critical Insight

Swift developers can now build concurrent data structures in pure Swift using carefully designed atomic APIs that were previously only accessible through C/C++.

The article reveals why atomic strong references might be the most interesting feature, and what double-wide primitives enable for solving common concurrency problems.

About This Article

Problem

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.

Solution

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.

Impact

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.