在异步任务中锁定并解锁dispatch_queue_t

时间:2016-04-21 23:11:26

标签: swift grand-central-dispatch

我希望锁LockQueue2完成流程,解锁时LockQueue2number中显示“数字为:dispatch_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)

1 个答案:

答案 0 :(得分:0)

如果您正在处理简单的同步任务,就像使用串行队列一样:

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)
坦率地说,信号量可能是我最后的解决方案,通常,其他方法更优雅地处理这个问题。例如,我可能在处理异步进程时使用异步NSOperation子类:它需要更多的预先设置,但是非常优雅地处理异步任务。有关强大的示例,请参见WWDC 2015 Advanced NSOperations