Difference between queuing with `sync` and using a work item with the `.wait` flag?

I study Apple GCD and watch a video Parallel programming with GCD in Swift 3 .

At 16:00 in this video, the DispatchWorkItem flag, called .wait , is .wait , and the functionality and diagram show what I thought of myQueue.sync(execute:) .

. wait diagram

So my question is: what is the difference between:

 myQueue.sync { sleep(1); print("sync") } 

and

 myQueue.async(flags: .wait) { sleep(1); print("wait") } // NOTE: This syntax doesn't compile, I'm not sure where the `.wait` flag moved to. // `.wait` Seems not to be in the DispatchWorkItemFlags enum. 

Both approaches seem to block the current thread while they expect the named queue:

  • Complete any current or previous work (if it is consistent)
  • Fill in the specified block / work item

My understanding of this should be somewhere that I am missing?

+6
source share
1 answer

.wait not a flag in DispatchWorkItemFlags , which is why your code

 myQueue.async(flags: .wait) { sleep(1); print("wait") } 

not compiled.

wait() is a DispatchWorkItem method and just a wrapper for dispatch_block_wait() .

 /*! * @function dispatch_block_wait * * @abstract * Wait synchronously until execution of the specified dispatch block object has * completed or until the specified timeout has elapsed. 

A simple example:

 let myQueue = DispatchQueue(label: "my.queue", attributes: .concurrent) let workItem = DispatchWorkItem { sleep(1) print("done") } myQueue.async(execute: workItem) print("before waiting") workItem.wait() print("after waiting") dispatchMain() 
+8
source

All Articles