0

In this example, what's the difference between queue.sync and queue.async

var queue = DispatchQueue(label: "sample", qos: .background)

queue.sync {
   //some code
}
queue.async {
   //some code 
}
tHatpart
  • 1,302
  • 3
  • 12
  • 27
  • See [What happens if dispatch on same queue?](https://stackoverflow.com/questions/58600133/what-happens-if-dispatch-on-same-queue/58600994#58600994). It contains a lot more than what you ask... – mfaani Feb 05 '20 at 22:02
  • Also see my comment on Mohsen's answer below. It my help you understanding things better – mfaani Feb 05 '20 at 22:20

1 Answers1

1

Both snippets append a closure to the queue.

But there is one difference.

Sync

Synch will wait for the closure to be executed before processing the next line.

So in this case, the print("Hello") is executed always after the closure.

queue.sync {
   //some code
}
print("Hello")

Async

In this case the closure is added to the queue and then the next line is executed. So the print("Hello") could be executed before the closure.

queue.async {
   //some code
}
print("Hello")
mfaani
  • 33,269
  • 19
  • 164
  • 293
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • 1
    Also, calling `sync` might lead to dealock (especially with `DispatchQueue.main`). That cannot happen with `async`. – Sulthan Feb 05 '20 at 22:23