Created
January 4, 2023 05:44
-
-
Save boraseoksoon/59b2e10f0b78b773370ba13462c4bb1d to your computer and use it in GitHub Desktop.
Swift actor the most boring data race example
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 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