Skip to content

Instantly share code, notes, and snippets.

@aainaj
Last active April 3, 2023 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aainaj/a7ca2a98d0cd791566c46a7a7da5309d to your computer and use it in GitHub Desktop.
Save aainaj/a7ca2a98d0cd791566c46a7a7da5309d to your computer and use it in GitHub Desktop.
Dispatch Barrier to solve race condition
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