GCD II
Async vs Sync.
GCD II
Async vs Sync.
0
0
Checkbox to mark video as read
Mark as read

Async vs Sync

All the queues we've seen so far have been executed with the keyword async. However, there's an option to execute them with sync. The difference is that async tasks will not run until sync tasks have finished their execution.

Let's see an example using two queues with async.

DispatchQueue.global(qos: .background).async {
    for i in 0..<5 {
        print("👾 \(i)")
    }
}

DispatchQueue.global(qos: .userInteractive).async {
    for i in 0..<5 {
        print("🤖 \(i)")
    }
}

As we mentioned earlier, .userInteractive has higher priority than .background.

🤖 0
👾 0
👾 1
🤖 1
🤖 2
🤖 3
🤖 4
👾 2
👾 3
👾 4

If we execute our background queue with sync, we will see that this queue finishes execution first.

DispatchQueue.global(qos: .background).sync {
    for i in 0..<5 {
        print("👾 \(i)")
    }
}

DispatchQueue.global(qos: .userInteractive).async {
    for i in 0..<5 {
        print("🤖 \(i)")
    }
}


👾 0
👾 1
👾 2
👾 3
👾 4
🤖 0
🤖 1
🤖 2
🤖 3
🤖 4

Conclusion

Unless it's for something specific, we will generally use the async method.

0 Comments

Join the community to comment

Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy