-1

[iOS, Swift] for a serial queue, sync and async will give same output ? as there is only 1 thread available.

i know sync will wait till method finish its execution. and async will return control immediately, without waiting for method to finish execution.

but in terms of serial queue. where there is only 1 thread. and In order for task2 to start task1 have to finish its execution.

looks like it will be giving same behavior on sync and async. Something is not correct here i feel. Can you give me example ?

submitting 4 async tasks to serial queue, that means task1 have to finish first, before task2 start, task2 have to finish first, before task3 start task3 have to finish first, before task4 start

and we are in serial queue, so only 1 thread available.

Matrix
  • 7,477
  • 14
  • 66
  • 97
  • The difference is in the behaviour of the task that is enqueuing the work; Async lets that task continue, while sync will block that task until the queued task is complete. – Paulw11 Nov 25 '19 at 08:43
  • but there is only 1 thread. So execution of order should be same on sync and async serial queue ? – Matrix Nov 25 '19 at 08:46
  • The execution order in the target queue will be the same, but the difference is whether the submitting queue blocks (`sync`) or not (`async`) – Paulw11 Nov 25 '19 at 08:47
  • See the discussion and examples in [this answer](https://stackoverflow.com/questions/42145427/how-does-a-serial-queue-private-dispatch-queue-know-when-a-task-is-complete/42146095#42146095) – Paulw11 Nov 25 '19 at 08:50

1 Answers1

3

looks like it will be giving same behavior on sync and async.

Yes, the behavior of the serial queue, itself, with respect to other items in that queue, doesn’t change depending upon whether you use sync or async. The only difference is the relationship between the current thread and the dispatch queue’s thread.

Consider:

queue.sync { print("A") }
queue.sync { print("B") }
queue.sync { print("C") }
queue.sync { print("D") }
print("E")

That will produce:

A
B
C
D
E

Compare that to:

queue.async { print("A") }
queue.async { print("B") }
queue.async { print("C") }
queue.async { print("D") }
print("E")

Because the current thread won’t wait for the tasks dispatched asynchronously to the serial queue, that will produce:

E
A
B
C
D

So, the behavior of A-D, all running on the queue, is unchanged. The only question is where that falls in comparison to E, generated by the the current thread. (FWIW, in this asynchronous example, E could actually happen anywhere before, in the middle of, or after A-D, but in practice, you'll see it run before the other queue gets to the asynchronously dispatched A-D.)

Rob
  • 415,655
  • 72
  • 787
  • 1,044