Created
June 29, 2024 22:30
-
-
Save dkyowell/a705ded56831e0da8ffda3f6474ddf7e to your computer and use it in GitHub Desktop.
Why doesn't Swift 6 detect as a data race?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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