使用“sync”分派到队列与使用带有“.wait”标志的工作项之间的区别?

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

我正在学习 Apple 的 GCD,正在观看视频 Concurrent Programming With GCD in Swift 3

在此视频的 16:00 处,DispatchWorkItem 的标志被描述为 .wait,功能和图表都准确地显示了我认为 myQueue.sync(execute:) 的用途.

所以,我的问题是;有什么区别:

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

并且:

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.

似乎这两种方法在等待命名队列时都阻塞了当前线程:

  1. 完成任何当前或之前的工作(如果是连续的)
  2. 完成给定的 block/work 项目

我对这个的理解一定有偏差,我错过了什么?

.wait 不是 DispatchWorkItemFlags 中的标志,这就是为什么 你的代码

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

不编译。

wait() is a method of DispatchWorkItem 只是一个包装器 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.

简单示例:

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()