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:
My understanding of this must be off somewhere, what am I missing?
Here are how operation queues are different from dispatch queues: In operation queues, you can set priority for your operations and also you can add dependencies to the operations which means you can define that some operation execute only after the completion of other operations.
Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.
A DispatchWorkItem encapsulates work to be performed on a dispatch queue or within a dispatch group. You can also use a work item as a DispatchSource event, registration, or cancellation handler.
With GCD, you add blocks of code or work items to dispatch queues and GCD decides which thread to execute them on. As you structure your code, you'll find code blocks that can run simultaneously and some that should not. This allows you to use GCD to take advantage of concurrent execution.
.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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With