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.
Be the first to comment