Created
March 20, 2017 20:58
-
-
Save drosenstark/64bd538eed5a9382f1fede9e880b3947 to your computer and use it in GitHub Desktop.
Locking Demo with GCD and Swift (Playground)
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 | |
// 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