-2

so what I understood from basics is: the async task will not block the current queue, sync task will block the current queue until that task finishes.

but when I run code on the main queue, just to print number from 1 to 100, it is giving me the same output.

use case -1
        DispatchQueue.global(qos: .default).async {
        DispatchQueue.main.async {
            for i in 0...100{
                print(i)
                sleep(arc4random() % 5)
            }
        }
        }

==============
use case -2        
        DispatchQueue.global(qos: .default).async {
            DispatchQueue.main.sync {
                for i in 0...100{
                    print(i)
                sleep(arc4random() % 5)
            }
        }

what can be the reason for getting the same output for async vs sync on the main queue?

Is it because the serial queue will have only one thread associated with it?

Matrix
  • 7,477
  • 14
  • 66
  • 97
  • I thought because tasks are async, so output can be printed in any order. since we don't know when async tasks finish execution. – Matrix Jan 13 '20 at 08:42
  • I just wanted to check, does Dispatch.main.async Vs Dispatch.main.sync produce different output in any case? – Matrix Jan 13 '20 at 08:47
  • Main Queue is serial. When you perform first async call you add to that serial queue some work(first for loop). And then you add to main(serial) queue other work(second for loop). An main queue perform that pieces of work one by one. First perform all first loop and only after that perform second loop. Syns/async don't influence on it. Sync that you use in second case block `DispatchQueue.global(qos: .default)` and make it wait until second for loop finished. – Grigory Serebryanyy Jan 13 '20 at 08:48
  • I have edited my question a bit, so I am not writing both use case 1 and use case 2, I am running them separately. and then comparing their outputs. – Matrix Jan 13 '20 at 08:51
  • Does this answer your question? [Difference between DispatchQueue.main.async and DispatchQueue.main.sync](https://stackoverflow.com/questions/44324595/difference-between-dispatchqueue-main-async-and-dispatchqueue-main-sync) – ViTUu Jan 13 '20 at 09:03

1 Answers1

2

When you, a queue, say DispatchQueue.main.sync or DispatchQueue.main.async, that does not affect how the main queue behaves; it affects how you behave, ie whether you wait before doing what comes after the call. But you have nothing after the call so there is no distinction to draw. Your “test” does not test anything.

matt
  • 515,959
  • 87
  • 875
  • 1,141