Should `MutableRef` and `Ref` conditionally conform to `Sendable`?

I was just playing around with the new MutableRef and Ref types in some async code and realized that neither of those types conform to Sendable conditionally. I think both can and should safely add the conditional conformance. Similar to how the Span types conform to Sendable conditionally.

Ref

Is Copyable and provides multiple read-only views to memory. If the underlying type is Sendable then Ref should be safely Sendable as well.

MutableRef

Seems a bit tricker but I think is safe to conditionally conform as well since it's ~Copyable so only a single mutable ref can exist at any point in time. The compiler is already enforcing that you can't have overlapping concurrent access to var's and if it is stored as a let then the same reasoning as Ref applies.

@Alejandro and @Joe_Groff what do you think about this?

Well I just saw the amendment PR so that answers my question.

3 Likes

Do we have the tools to do this properly? Swift's Sendable roughly acts like Rust's Send for value types and Sync for reference types, but in Rust a non-mutable reference is only Send if its referent is Sync. Currently I don't think Swift has any types with interior mutability that can't handle this (atomics are meant to be shared), but if Ref is Sendable when its referent is Sendable, we'll never be able to add something like Cell to the language at all (at least not safely).

1 Like

We already made Span and MutableSpan be conditionally Sendable, so doing the same for Ref and MutableRef doesn't create new problems for us, at least.

1 Like