What is the recommended way to ensure atomic execution? DispatchQueue? UnfairLock? Other locks? Other ways?

Asked on 08/08/2024

1 search

The recommended way to ensure atomic execution in Swift, as presented at WWDC, involves using the new low-level synchronization primitives introduced in Swift 6. Specifically, the synchronization module introduces atomics and mutexes:

  1. Atomics: These are generic over any type that provides an efficient, lock-free implementation on the platform. Atomic values should always be stored in let properties for safe concurrent access. All operations on atomics are explicit with memory ordering arguments.

  2. Mutexes: Similar to atomics, a mutex should be stored in a let property and can be safely accessed concurrently. All accesses to the storage protected by the mutex are via the closure passed to the withLock method, which ensures mutually exclusive access.

For more details, you can refer to the session "What’s new in Swift" at the timestamp 28:51.

Relevant Sessions

  1. What’s new in Swift
  2. Migrate your app to Swift 6
  3. A Swift Tour: Explore Swift’s features and design
  4. What’s new in Xcode 16