-3

I have written a sample code for getting deep into the threading concepts as below.

print("a")
DispatchQueue.global(qos: .default).async {
   print("b")
   DispatchQueue.global(qos: .default).async {
      print("c")
      DispatchQueue.global(qos: .default).async {
        print("d")
        DispatchQueue.global(qos: .default).async {
         print("e")
        }
        print("f")
      }
      print("g")
   }
   print("h")
}
print("i")

OUTPUT

a
i
b
h
c
g
d
f
e

How the output seems like this. What is actually happening inside?

Saranjith
  • 11,242
  • 5
  • 69
  • 122

3 Answers3

2

There are two basic behaviors:

  1. As the name implies an asynchronously dispatched queue is always executed after the enclosing scope – {} – exits.

    So i is printed before b, h is printed before c etc.

  2. A dispatch queue works serial by default, all tasks are executed one after another

    So the consecutive order is i - b - h - c - g - d - f - e

vadian
  • 274,689
  • 30
  • 353
  • 361
  • `DispatchQueue.global` is a concurrent not serial a way from the fact that the op nestes the code which make it look serial in printing but not in run as consider making an api request – Shehata Gamal Dec 12 '18 at 11:28
1

The idea is any 2 lines 1 of them is

DispatchQueue.global(qos: .default).async

the second will run first , so this

print("a")
DispatchQueue.global(qos: .default).async {  
 print("b")
}
print("i")

gives

a // comes first
i // printed first before queue as the queue dispatches the execution with some delay
b // printed second

Then go inside the async and apply the same rule

   DispatchQueue.global(qos: .default).async {
      print("c")
      DispatchQueue.global(qos: .default).async {  
      print("d")
      }
      print("g")
   }
   print("h")


h

c

g

d
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

On each DispatchQueue.global context was splitting up, and cost of dispatching higher than simple print, that's all.