Group Group Group Group Group Group Group Group Group

Question Chap 23 GCD asynchronous work queues

#1

Question on the following function in the book. Trying to get a better understanding of what is going on

“// 1
func execute(backgroundWork: @escaping () -> Result,
mainWork: @escaping (Result) -> ()) {
// 2
queue.async {
let result = backgroundWork()
// 3
DispatchQueue.main.async {
mainWork(result)
}
}
}”

The 1st closure passed to this function is put on an queue in an asynch manner, then the function will immediately place the 2nd closure on the main queue asynchronously. The 2nd closure requires the “result” constant as an input parameter, what coordination takes place under the covers to make sure the result is passed from one asynchronous task to the other asynchronous task?

#2

then the function will immediately place the 2nd closure on the main queue asynchronously

Not so. The call to DispatchQueue.main.async is part of the code block that has been passed in to the call to queue.async {}. So the queue will execute that block, first doing let result = backgroundWork(), then doing DispatchQueue.main.async { mainWork(result) }. Some indenting and comments will help you see it:

func execute(backgroundWork: @escaping () -> Result,
mainWork: @escaping (Result) -> ()) {
    queue.async {
        // start of block in queue
        let result = backgroundWork()
        DispatchQueue.main.async {
            mainWork(result)
        }
       // end of block in queue
   }
}
1 Like
#3

I get it now. Thanks for your very succinct explanation. It is very appreciated!

closed #4

This topic was automatically closed after 166 days. New replies are no longer allowed.