使用`sync`调度队列和使用带有.wait`标志的工作项之间的区别?

Sim*_*lGy 6 grand-central-dispatch swift3

我正在学习Apple的GCD,并在Swift 3中观看视频并行编程与GCD.

在这个视频的16:00,DispatchWorkItem描述了一个标志.wait,并且功能和图表都显示了我的想法myQueue.sync(execute:).

等待图

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

myQueue.sync { sleep(1); print("sync") }
Run Code Online (Sandbox Code Playgroud)

和:

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.
Run Code Online (Sandbox Code Playgroud)

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

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

我对此的理解必须在某处,我错过了什么?

Mar*_*n R 9

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

myQueue.async(flags: .wait) { sleep(1); print("wait") }
Run Code Online (Sandbox Code Playgroud)

不编译.

wait()是一种方法,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.
Run Code Online (Sandbox Code Playgroud)

简单的例子:

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()
Run Code Online (Sandbox Code Playgroud)