Reputation: 59506
We all know there are good numbers and bad numbers in the universe.
I have the following synchronous function
func isGood(number:Int) -> Bool {
// synchronous connection
// ...
// returns a Bool
}
Of course I am not providing the secret implementation here, but you should know that it performs a synchronous internet connection and it does return
true
: if the Int
received as param is a "good number"false
: otherwiseNow, given the 100 integers from 0 to 99, I want to know if at least 51 of them are good numbers.
I could write something like this.
func majorityIsGood() -> Bool {
var count = 0
for i in 0...99 {
if isGood(i) {
count++
if count > 50 {
return true
}
}
}
return false
}
But performing 100 (in the worst case scenario) synchronous call to isGood
will require too much time. I need the answer as fast as possible.
I would prefer something like this
func majorityIsGood(completion:(good:Bool) -> ()) {
var goodNums = 0
var badNums = 0
var resultFound = false
for i in 0...99 {
dispatch_async(DISPATCH_QUEUE_CONCURRENT) {
let isGood = isGood(i)
// lineA
// begin lock on (resultFound)
if !resultFound {
if isGood {
goodNums++
} else {
badNums++
}
if goodNums > 50 || badNums >= 50 {
resultFound = true
completion(good: goodNums > 50)
}
}
// end lock on (resultFound)
// lineB
}
}
}
lineA
and lineB
in Swift?Thank you in advance.
Upvotes: 3
Views: 448
Reputation: 9148
serial queue
can be used to synchronize access to a specific resource.NSOperation
cancellation.Here's the code
func majorityIsGood( completion: ((good:Bool) -> Void) ) {
var goodNums = 0
var badNums = 0
var resultFound = false
let serialQueue = dispatch_queue_create("com.unique.myQueue", DISPATCH_QUEUE_SERIAL)
for i in 0...99 {
dispatch_async(DISPATCH_QUEUE_CONCURRENT) {
let _isGood = isGood(i)
// lineA
dispatch_async(serialQueue){
if !resultFound {
if _isGood {
goodNums++
} else {
badNums++
}
if goodNums > 50 || badNums >= 50 {
resultFound = true
completion(good: goodNums > 50)
}
}
}
// lineB
}
}
}
Upvotes: 2
Reputation: 2159
Build on the shoulders of giants!
lock
/unlock
mechanism.NSOperation
s which provide a cancellation mechanism (although it should be noted that it is actually up to you to check the isCancelled
flag at appropriate points in your NSOperation
so that you can stop whatever work it is doing.Upvotes: 1