Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nickarthur/a171d1762db2a677407d2428f543f698 to your computer and use it in GitHub Desktop.
Save nickarthur/a171d1762db2a677407d2428f543f698 to your computer and use it in GitHub Desktop.
Locking Demo with GCD and Swift (Playground)
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
// CHANGE THIS TO TRUE FOR the lock queue to be used
let useLocks = false
var counter : Int = 0
func incrementCounter(contextName:String) {
let originalCounterValue = counter
counter = counter + 1
if counter != originalCounterValue + 1 {
fatalError("\(contextName):\(counter) Another caller got in here and stepped on our data! ")
} else {
print("\(contextName):\(counter) OK")
}
}
let lockQueue = DispatchQueue(label: "lock")
func callIncrement(name:String, useLock: Bool) {
if useLock {
lockQueue.async {
incrementCounter(contextName: name)
}
} else {
incrementCounter(contextName: name)
}
}
DispatchQueue.global(qos: .background).async {
for _ in 0..<100 {
callIncrement(name: "ONE", useLock: useLocks)
}
}
DispatchQueue.global(qos: .background).async {
for _ in 0..<100 {
callIncrement(name: "TWO", useLock: useLocks)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment