问题
I'm learning about Apple's GCD, and watching the video Concurrent Programming With GCD in Swift 3.
At 16:00 in this video, a flag for DispatchWorkItem
is described called .wait
, and the functionality and diagram both show exactly what I thought myQueue.sync(execute:)
was for.
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.
Seems like both approaches block the current thread while they wait for the named queue to:
- Finish any current or prior work (if serial)
- Complete the given block/work item
My understanding of this must be off somewhere, what am I missing?
回答1:
.wait
is not a flag in DispatchWorkItemFlags
, and that is why
your code
myQueue.async(flags: .wait) { sleep(1); print("wait") }
does not compile.
wait() is a method of DispatchWorkItem 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.
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()
来源:https://stackoverflow.com/questions/38105105/difference-between-dispatching-to-a-queue-with-sync-and-using-a-work-item-with