[英]Concurrency and lock in Swift
我们都知道宇宙中有很多数字和坏数字 。
我有以下同步功能
func isGood(number:Int) -> Bool {
// synchronous connection
// ...
// returns a Bool
}
当然,我不是在这里提供秘密实现,但你应该知道它执行同步互联网连接并确实返回
true
:如果作为参数收到的Int
是一个“好数字” false
:否则 现在,假设从0到99的100个整数,我想知道它们中至少有51个是好数字。
我可以写这样的东西。
func majorityIsGood() -> Bool {
var count = 0
for i in 0...99 {
if isGood(i) {
count++
if count > 50 {
return true
}
}
}
return false
}
但是执行100(在最坏的情况下)同步调用isGood
将需要太多时间。 我需要尽快得到答案。
我更喜欢这样的东西
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
和lineB
之间的代码块? 先感谢您。
serial queue
可用于同步对特定资源的访问。 NSOperation
取消。 这是代码
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
}
}
}
建立在巨人的肩膀上!
lock
/ unlock
机制。 NSOperation
数组提供取消机制的情况(尽管应该注意到它实际上取决于你检查在你的NSOperation
中的适当点处的isCancelled
标志,这样你就可以停止正在做的任何工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.