Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created January 4, 2023 05:44
Show Gist options
  • Save boraseoksoon/59b2e10f0b78b773370ba13462c4bb1d to your computer and use it in GitHub Desktop.
Save boraseoksoon/59b2e10f0b78b773370ba13462c4bb1d to your computer and use it in GitHub Desktop.
Swift actor the most boring data race example
import Foundation
class Class {
var i = 0
func decrease() {
i-=1
}
func increase() {
i+=1
}
func log() {
decrease()
increase()
print("class i : \(i)")
}
}
actor Actor {
var i = 0
func decrease() {
i-=1
}
func increase() {
i+=1
}
@objc nonisolated func log() {
Task {
await isolatedLog()
}
}
func isolatedLog() {
decrease()
increase()
print("actor i : \(i)")
}
}
let actor = Actor()
let `class` = Class()
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
actor.log()
}
// actor i : 0
// actor i : 0
// actor i : 0
// actor i : 0
// actor i : 0
// actor i : 0
// actor i : 0
// actor i : 0
// actor i : 0
// ...
// ..
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
`class`.log()
}
// class i : -3
// class i : -5
// class i : -5
// class i : -2
// class i : -2
// class i : -2
// class i : -5
// class i : 0
// class i : -2
// ...
// ..
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment