Skip to content

Instantly share code, notes, and snippets.

@boraseoksoon
Created January 4, 2023 05:46
Show Gist options
  • Save boraseoksoon/5ff333b28025bda4338ef07ce1b13693 to your computer and use it in GitHub Desktop.
Save boraseoksoon/5ff333b28025bda4338ef07ce1b13693 to your computer and use it in GitHub Desktop.
Swift actor the most boring race condition example
import Foundation
class Class {
func log2() {
print("class log2")
}
func log3() {
print("class log3")
}
}
actor Actor {
@objc nonisolated func log2() {
Task {
await isolatedLog2()
}
}
func isolatedLog2() {
print("actor log2")
}
@objc nonisolated func log3() {
Task {
await isolatedLog3()
}
}
func isolatedLog3() {
print("actor log3")
}
}
let actor = Actor()
let `class` = Class()
///
///
/// Race conditon
///
///
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
Task {
await actor.isolatedLog2()
await actor.isolatedLog3()
}
}
// actor log2
// actor log3
// actor log2
// actor log3
// actor log2
// actor log3
// actor log2
// actor log3
// ...
// ..
// .
// actor log2
// actor log3
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
actor.log2()
actor.log3()
}
// actor log2
// actor log2
// actor log2
// actor log2
// actor log2
// actor log2
// actor log2
// actor log3
// ...
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
`class`.log2()
`class`.log3()
}
// class log2
// class log2
// class log2
// class log2
// class log3
// class log2
// class log3
// class log3
// class log2
// class log3
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment