Last active
April 3, 2023 18:02
-
-
Save aainaj/a7ca2a98d0cd791566c46a7a7da5309d to your computer and use it in GitHub Desktop.
Dispatch Barrier to solve race condition
This file contains 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 | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
var value: Int = 2 | |
let concurrentQueue = DispatchQueue(label: "queue", attributes: .concurrent) | |
concurrentQueue.async(flags: .barrier) { | |
for i in 0...3 { | |
value = i | |
print("\(value) ✴️") | |
} | |
} | |
concurrentQueue.async { | |
print(value) | |
} | |
concurrentQueue.async(flags: .barrier) { | |
for j in 4...6 { | |
value = j | |
print("\(value) ✡️") | |
} | |
} | |
concurrentQueue.async { | |
value = 14 | |
print(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment