我希望lockLockQueue2
完成这个过程,当unlockLockQueue2
时,show“数字是:”number
indispatch_after
。
我需要这个输出:
数字设定值1
数字是1
数字设定值2
数字是2
数字设定值3
数字是3
let LockQueue = dispatch_queue_create("LockQueue", nil)
func test(num :Int){
var number = 0
let LockQueue2 = dispatch_queue_create("LockQueue2", nil)
dispatch_async(LockQueue){
LockQueue2.lock()
// any process or waiting
sleep(2)
dispatch_sync(LockQueue2) {
number = num
print("number set value ", number)
LockQueue2.unlock()
}
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)){
// any process or waiting
sleep(3)
dispatch_after(LockQueue2) {
print("number is :", number)//*** show number set in last dispatch ***
}
}
}
test(1)
test(2)
test(3)
最佳答案
如果您处理的是简单的同步任务,您可以使用串行队列:
let serialQueue = dispatch_queue_create("com.domain.app.serialqueue", nil)
func simpleSerialQueue(num: Int) {
var number = 0
dispatch_async(serialQueue){
sleep(2)
number = num
print("number set value: ", number)
}
dispatch_async(serialQueue) {
print("number is:", number)//*** show number set in last dispatch ***
}
}
simpleSerialQueue(1)
simpleSerialQueue(2)
simpleSerialQueue(3)
或者,如果有一个异步任务要等待它完成,则可以使用信号量:
let serialQueue = dispatch_queue_create("com.domain.app.serialqueue", nil)
func semaphoreExample(num: Int) {
var number = 0
let semaphore = dispatch_semaphore_create(0)
// this will fire in 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC * 2)), serialQueue) {
number = num
print("number set value: ", number)
dispatch_semaphore_signal(semaphore);
}
// this will start immediately, but will wait until the above semaphore is signaled
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
print("going to wait for semaphore")
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
print("number is:", number)
}
}
semaphoreExample(1)
坦率地说,信号量可能是我最后的解决方案,一般来说,其他方法处理这个问题更优雅。例如,在处理异步进程时,我可能会使用asynchronous
NSOperation
子类:它需要更多的预先设置,但处理异步任务非常得体。请参阅WWDC 2015Advanced NSOperations以获取可靠的示例。