Swift Proposal: Synchronous Mutual Exclusion Lock

submited by
Style Pass
2024-05-05 15:30:05

Not all code may be able (or want) to adopt actors. Reasons for this can be very varied, for example code may have to execute synchronously without any potential for other tasks interleaving with it. Or the async effect introduced on methods may prevent legacy code which cannot use Swift Concurrency from interacting with the protected state.

We propose a new type in the Standard Library Synchronization module: Mutex. This type will be a wrapper over a platform-specific mutex primitive, along with a user-defined mutable state to protect.

Mutex will be decorated with the @_staticExclusiveOnly attribute, meaning you will not be able to declare a variable of type Mutex as var. These are the same restrictions imposed on the recently accepted Atomic and AtomicLazyReference types. […] We do not want to introduce dynamic exclusivity checking when accessing a value of Mutex as a class stored property for instance.

Mutex is unconditionally Sendable regardless of the value it's protecting. We can ensure the safetyness of this value due to the transferring marked parameters of both the initializer and the closure inout argument.

Leave a Comment