16

Does this always print in the order of 1 5 2 4 3?

print("1")
DispatchQueue.main.async {
    print("2")
    DispatchQueue.main.async {
        print(3)
    }
    print("4")
}
print("5")

I feel the answer is no, but I cannot explain it and hope someone could clarify my understanding. Thank you!

Shruti Thombre
  • 989
  • 4
  • 11
  • 27
Unikorn
  • 1,140
  • 1
  • 13
  • 27
  • 1
    Yes, it is obvious for 1 ,5 after that it switches to main queue prints 2, Then you again request main queue task but it will not wait for it and prints 4 and then 3 – Prashant Tukadiya Oct 10 '18 at 05:36
  • 3
    You need to clarify one thing, whether `print("1")` is executed in the main thread or not. – OOPer Oct 10 '18 at 05:38
  • 1
    why would it matter? It would always execute first. – Unikorn Oct 10 '18 at 05:43
  • I suspect is due to the execution order: print("1") // 1. executes prints 1 DispatchQueue.main.async { // 2. switches to main thread print("2") // 4. executes print 3 DispatchQueue.main.async { // 5. switches to main thread print(3) // 7. executes print 3 } print("4") // 6. executes print 4 } print("5") // 3. executes print 5 – Unikorn Oct 10 '18 at 06:11
  • @OOPer, please forgive my ignorant for my earlier remark thinking it will always execute first. – Unikorn Oct 10 '18 at 06:42
  • 1
    @Unikorn, no worries, in fact I'm not good at writing a good picture like Cristik. Now you have two splendid answers and you know why I wrote the comment. – OOPer Oct 10 '18 at 06:53

2 Answers2

16

It depends on which thread you start the operation.

If you start from the main then, then you get 1, 5, 2, 4, 3

If you start from a background thread, then most of the time you'll get them same result (1, 5, 2, 4, 3), however this is not guaranteed as the background thread can be put to sleep at any time by the OS, and if this happens right before the print(5)call, then 5 will be the last to be printed.

Just a note that if the code from the question is the only one in your app/playground, then you might be surprised by running into partial prints, as the app/playground exits as soon as it hits the print(5) line, before having a chance to execute the async dispatch. To circumvent this, you can make sure that RunLoop.current.run() gets executed on the main thread as the last part of your code.

Here are some diagram that try to illustrate what happens in the main-thread-only scenario, and the one where a background thread is involved:

enter image description here enter image description here

Cristik
  • 30,989
  • 25
  • 91
  • 127
11

You will always get 1, 2, 4, 3. The 5 will always be after the 1. But where it ends up in relation to the others depends on what queue the whole thing started on.

If this is started from the main queue then 5 will always be between 1 and 2.

Here's why:

This code starts on the main queue. 1 is printed. You then enqueue another block to run asynchronously on the main queue so that block will be run after the current block completes and the main queue gets to the end of the current run loop. The code continues to the next line which is to print 5. The current block ends and the next block on the main queue is run. This is the block of the first call to DispatchQueue.main.async. As this block runs it prints 2 (so now we have 1 5 2). Another block is enqueued to the main queue just like the last one. The current block continues and prints 4 (so now we have 1 5 2 4). The block ends and the next block on the main queue is run. This is the final block we added. That block runs and it prints 3 giving the final output of 1 5 2 4 3.

If you started on some background queue then 5 can appear anywhere after 1 but for such simple code, the 5 will most likely still appear between 1 and 2 but it can appear anywhere after the 1 in a general case.

Here's why:

This code starts on a background queue. 1 is printed. You then enqueue another block to run asynchronously on the main queue so that block will be run after the current main queue run loop completes. The code continues to the next line which is to print 5. The current block ends. The block added to the main queue is run in parallel to the background queue. Depending on the time of when the block added to the main queue is run in relation to the remaining code on the background queue is run, the output of print("5") can be intermingled with the prints from the main queue. This is why the 5 can appear anywhere after the 1 when started from the background.

But the simple code in the question will likely always give 1 5 2 4 3 even when started on the background because the code is so short and takes so little time.

Here's some code that puts the 5 elsewhere:

func asyncTest() {
    print("1")
    DispatchQueue.main.async {
        print("2")
        DispatchQueue.main.async {
            print(3)
        }
        print("4")
    }

    for _ in 0...1000 {
    }

    print("5")
}

DispatchQueue.global(qos: .background).async {
    asyncTest()
}

The existence of the loop causes the 5 to take a little longer before it appears which allows the main queue to get executed some before 5 is printed. Without the loop, the background thread executes too quickly so the 5 appears before 2.

If running this test in a playground, add:

PlaygroundPage.current.needsIndefiniteExecution = true

to the top of the playground (just after the imports). You will also need:

import PlaygroundSupport
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I ran this in playground 10+ times and always get : 1 5 2 4 3 – Unikorn Oct 10 '18 at 05:44
  • 1
    Most likely you are starting this on the main queue so that will always give you that result, just as I stated in my answer. – rmaddy Oct 10 '18 at 05:46
  • 1
    @Unikorn I added a lot more explanation to my answer. Have a look and see if that clarifies things. – rmaddy Oct 10 '18 at 06:30
  • 1
    I ran the example code on the playground a few times. It still gives me the result. What is the probability that 5 will not be between 1 and 2? – Rakesha Shastri Oct 10 '18 at 06:31
  • 1
    @RakeshaShastri Every time I run the code in my answer I get the 5 between the 4 and 3. Maybe you have a much faster computer. Try making the loop bigger. – rmaddy Oct 10 '18 at 06:33
  • @rmaddy yes. It's at the end now. I added a few more zeroes. – Rakesha Shastri Oct 10 '18 at 06:33
  • Thank you @rmaddy & Cristik for the beautiful explanation!! Thank you!! Everyone gets an upvote tonight!!! – Unikorn Oct 10 '18 at 07:04