Aggressor Aggressor - 1 year ago 185
Swift Question

Why is dispatch_sync doing work on the main thread when it uses DISPATCH_QUEUE_PRIORITY_BACKGROUND?

Working on getting some concurrency going for my app. I have a snippet of code I'm curious about what thread it exists on.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
// For each location, update the user location
for location in locations

func updateUserLocation(location:CLLocation)

When I run this, this code correctly (according to what I think is happening) gets dispatched to another thread.

enter image description here

What confuses me is why changing the dispatch call to a
makes it run on the main thread:

dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))


enter image description here

The reason I am confused, is I (think) specify a background thread. From my understanding, I am making the main thread wait while I dispatch work to a background thread. But that isn't whats happening, the main thread continues to do the work. Is this an optimization done by the OS? Should this work be done on another thread?

Could you clarify where my theory is wrong on this?

Answer Source

I believe locationManager is called on main thread, dispatch_sync will cause the main thread blocked until the block finishes executing, so since the main thread will block and can't do anything, why not use the main thread to execute the block ? I think it's an optimization of GCD.

The GCD Reference says:

As an optimization, this function invokes the block on the current thread when possible.

You can't assume block you submit to dispatch_queue will execute in any threads, dispatch_queue doesn't attach to any specific threads(except for the main queue).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download