What is the recommended way to ensure atomic execution

Asked on 08/08/2024

1 search

The recommended way to ensure atomic execution in Swift is by using the new low-level 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, similar to the C and C++ memory model.

  2. Mutexes: Like 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 (28:51).