Difference between dispatching to a queue with `sync` and using a work item with a `.wait` flag?

雨燕双飞 提交于 2019-12-10 13:18:21

问题


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:

  1. Finish any current or prior work (if serial)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!