0

so i know we should never call dispatch_sync on main queue, as its a serial queue. so the below code will crash in xcode:

 DispatchQueue.main.sync {
            print("hello world")
        }

but i am not able to understand 100% why it is going to crash or deadlock ?

can someone explain with some drawing because i don't have 100% proof explanation that why it is going to crash or deadlock.

i know main queue is serial queue. so it executes tasks one by one. suppose we have task A running on main queue and if i add another taskB on main queue then task B only starts after taskA finishes.

and i also know that main queue should only perform UI specific tasks.

but its just i don't have 100% proof explanation of why above code will crash / deadlock.

can someone explain with some kind of simple drawing.

Matrix
  • 7,477
  • 14
  • 66
  • 97
  • Does this answer your question? [DispatchQueue crashing with main.sync in Swift](https://stackoverflow.com/questions/49258413/dispatchqueue-crashing-with-main-sync-in-swift) – IloneSP Jan 08 '20 at 16:05
  • When called from the main thread it will deadlock because the call to `sync` has to block until the closure completes, but the closure will never complete because the main thread is blocked. The OS can detect this kind of deadlock and turn it into a crash. Note that it will neither crash nor deadlock if called from some other thread. – Rudedog Jan 08 '20 at 16:06
  • looking for some graphical or diagram representation for better understanding. – Matrix Jan 08 '20 at 16:07

1 Answers1

1

i know main queue is serial queue. so it executes tasks one by one. suppose we have task A running on main queue and if i add another taskB on main queue then task B only starts after taskA finishes.

Correct

and i also know that main queue should only perform UI specific tasks.

Not correct. The UI must only be updated on the main queue but you can do whatever you want on the main queue. You can handle data on the main queue if it fits that particular application. If you're handling a lot of data and don't want to freeze the UI, then you would want to get off the main queue.

but its just i don't have 100% proof explanation of why above code will crash / deadlock.

// doing work...

DispatchQueue.main.sync { // stop the main thread and wait for the following to finish

    print("hello world") // this will never execute on the main thread because we just stopped it

}

// deadlock
trndjc
  • 11,654
  • 3
  • 38
  • 51