swift - lock and unlock dispatch_queue_t in async task -
i want lock lockqueue2
complete process , when unlock lockqueue2
show "number :" number
in dispatch_after
.
i need output :
number set value 1
number 1
number set value 2
number 2
number set value 3
number 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() // 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)){ // process or waiting sleep(3) dispatch_after(lockqueue2) { print("number :", number)//*** show number set in last dispatch *** } } } test(1) test(2) test(3)
if you're dealing simple synchronous tasks, are, can use serial queue:
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)
or if had asynchronous task wanted wait finish, use semaphore:
let serialqueue = dispatch_queue_create("com.domain.app.serialqueue", nil) func semaphoreexample(num: int) { var number = 0 let semaphore = dispatch_semaphore_create(0) // 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); } // start immediately, wait until above semaphore signaled dispatch_async(dispatch_get_global_queue(dispatch_queue_priority_default, 0)) { print("going wait semaphore") dispatch_semaphore_wait(semaphore, dispatch_time_forever) print("number is:", number) } } semaphoreexample(1)
frankly, semaphores solution of last resort, generally, other approaches handle more elegantly. example, might use asynchronous nsoperation
subclass when dealing asynchronous processes: requires little more set up-front, handles asynchronous tasks gracefully. see wwdc 2015 advanced nsoperations robust example.
Comments
Post a Comment