why is it legal to mutate an actor's nonSendable property?
Asked Answered
L

1

9

The following code is legal in Swift 5.5 (beta):

class Dog {
    var name = "rover"
    var friend : Dog? = nil
}
actor MyActor {
    let dog = Dog()
}
func test() async {
    let act = MyActor()
    act.dog.name = "fido"
    act.dog.friend = Dog()
    act.dog.friend?.name = "fido"
}

Why is this legal? The dog property is shared state, isn't it? Aren't we in danger of accessing the actor's dog on different threads simultaneously? Isn't that what actors are supposed to protect us from?

Curiously, if the actor's dog property were declared with var instead of let, we'd be compelled to say await during access. Why does that make a difference? Dog is a reference type; it is mutable in place, and it is mutable in exactly the same way regardless of whether it is declared with let or var.

Lisabeth answered 20/8, 2021 at 15:28 Comment(4)
Basically I'm wondering whether I've found a bug and looking for a sanity check before I report it.Lisabeth
@Rob So your answer is that it is up to you (meaning me) to Don't Do That? What then of the assertion in the proposal that "all cross-actor references can only involve types that conform to Sendable"?Lisabeth
(1) No they're not. They're claiming that the compiler will catch me exactly because Dog is not Sendable. (2) You have not explained what sense it makes that if the dog declaration is var we are forced to use await for access, but if the dog declaration is let, we are not. A constant reference to a nonSendable reference type is not more thread-safe than a var reference!Lisabeth
OK, I went ahead and filed this as a bug.Lisabeth
A
6

You are right that such access is unsafe and Swift 5.5 today does not prevent this, unless you pass the -warn-concurrency flag explicitly.

Please refer to the Staging in Sendable checking proposal (and forums post which discuss the rollout plan of the checking feature).

You can also read about the general plan with regards to concurrency safety between now in Swift 5.5 and Swift 6 in the roadmap update here: Concurrency in Swift 5 and 6.

Ammadas answered 24/8, 2021 at 11:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.