Swift's new Synchronization framework introduces Mutex, a modern lock for thread-safe data access. Unlike traditional locks, Mutex enforces strict ownership where only the thread that locked it can unlock it. The framework provides a withLock method for safe mutable access and works seamlessly with Swift Concurrency by being unconditionally Sendable. This allows wrapping non-Sendable types safely without the overhead of actors. While actors are great for async scenarios, Mutex fills the gap for synchronous, immediate access needs and legacy code compatibility.
Table of contents
What is a Swift Lock?Using Swift’s Mutex lock from the Synchronization frameworkA lock that works great with Swift ConcurrencyShouldn’t I use an actor instead of locks in Swift Concurrency?Sort: