0

Here I've a query about Difference between Threads

  • Difference Between DispatchQueue.global().sync , DispatchQueue.global().async, DispatchQueue.main.sync and DispatchQueue.main.sync

Here's some questions where i do R&D.

When I use DispatchQueue.global().sync, DispatchQueue.global().async and DispatchQueue.main.async below Code it works perfectly

func loadimage(_ url: URL)
{
    DispatchQueue.global().sync { // Here i used DispatchQueue.main.async , DispatchQueue.global().async and DispatchQueue.main.async
         if let data1 = try? Data(contentsOf: url){
           if let img = UIImage(data: data1){
             DispatchQueue.main.async {
                self.imgView.image = img
             }
           }
        }
    }
}

But when I use DispatchQueue.main.sync the application crashes.

func loadimage(_ url: URL)
{
    DispatchQueue.main.sync {
         if let data1 = try? Data(contentsOf: url){
           if let img = UIImage(data: data1){
             DispatchQueue.main.async {
                self.imgView.image = img
             }
           }
        }
    }
}

And I get below error on DispatchQueue.main.sync Here

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

piet.t
  • 11,718
  • 21
  • 43
  • 52
steveSarsawa
  • 1,559
  • 2
  • 14
  • 31

1 Answers1

0

If you call print(Thread.isMainThread) you probably will see 1 as output. If so you code was executed in main queue.

DispatchQueue.main.sync function pause current thread until code will be executed. But if you run in main queue, you pause main queue and try to execute task in main queue. But it paused. If you call it from background queue, we will:

  1. pause bg queue
  2. execute task in main queue
  3. continue in bg queue.

This logic works for serial queues like main queue.


If you perform async task, you just put this task in queue without pause. When all other task in queue will completed, your code start to execute.

If you have concurent queue, this code may work fine. Concurrent queue can switch between task when executing. You can read more about it in this topic.

Gralex
  • 4,285
  • 7
  • 26
  • 47