我正在了解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.
似乎这两种方法在等待命名队列时阻塞当前线程:
我对此的理解必须在某处,我缺少什么?
答案 0 :(得分:9)
.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()