Skip to content

Instantly share code, notes, and snippets.

@dkyowell
Created June 29, 2024 22:30
Show Gist options
  • Save dkyowell/a705ded56831e0da8ffda3f6474ddf7e to your computer and use it in GitHub Desktop.
Save dkyowell/a705ded56831e0da8ffda3f6474ddf7e to your computer and use it in GitHub Desktop.
Why doesn't Swift 6 detect as a data race?
import Foundation
class MutableState {
var value: Int
init(value: Int) {
self.value = value
}
}
actor MutableStateGuardian {
private let state: MutableState
init() {
self.state = MutableState(value: 0)
Task {
await increment()
}
}
func increment() {
for _ in (1...100_000) {
state.value += 1
}
}
func stealState(thief: StateThief) {
thief.state = state
}
}
class StateThief {
var state: MutableState?
}
let mutableStateGuardian = MutableStateGuardian()
@MainActor // <- without @MainActor annotation, data race is detected
func testCircumvention() async -> Int {
let thief = StateThief()
Task {
await mutableStateGuardian.stealState(thief: thief)
}
while thief.state == nil {
try? await Task.sleep(nanoseconds: 1)
}
for _ in (1...100_000) {
thief.state!.value -= 1
}
return thief.state!.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment