为什么 dispatch_sync 在使用 DISPATCH_QUEUE_PRIORITY_BACKGROUND 时在主线程上工作?
Why is dispatch_sync doing work on the main thread when it uses DISPATCH_QUEUE_PRIORITY_BACKGROUND?
正在为我的应用程序获取一些并发性。我有一段代码,我很好奇它存在于哪个线程上。
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
{
self.updateUserLocation(location)
}
}
}
func updateUserLocation(location:CLLocation)
{
_controller?.centerMapOnUser()
}
当我 运行 执行此操作时,此代码(根据我认为正在发生的情况)正确地分派到另一个线程。
让我感到困惑的是为什么将调度调用更改为 sync
使其在主线程上 运行:
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
原因:
我感到困惑的原因是我(认为)指定了一个后台线程。据我了解,我在将工作分派给后台线程时让主线程等待。但事实并非如此,主线程继续进行工作。这是OS做的优化吗?这项工作应该在另一个线程上完成吗?
你能澄清一下我的理论错在哪里吗?
我相信locationManager
是在主线程上调用的,dispatch_sync
会导致主线程阻塞,直到block执行完,所以既然主线程会阻塞,什么也做不了,为什么不使用主线程来执行块?我认为这是对GCD的优化。
As an optimization, this function invokes the block on the current thread when possible.
您不能假设您提交给 dispatch_queue 的块将在任何线程中执行,dispatch_queue 不附加到任何特定线程(主队列除外)。
正在为我的应用程序获取一些并发性。我有一段代码,我很好奇它存在于哪个线程上。
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
{
self.updateUserLocation(location)
}
}
}
func updateUserLocation(location:CLLocation)
{
_controller?.centerMapOnUser()
}
当我 运行 执行此操作时,此代码(根据我认为正在发生的情况)正确地分派到另一个线程。
让我感到困惑的是为什么将调度调用更改为 sync
使其在主线程上 运行:
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
原因:
我感到困惑的原因是我(认为)指定了一个后台线程。据我了解,我在将工作分派给后台线程时让主线程等待。但事实并非如此,主线程继续进行工作。这是OS做的优化吗?这项工作应该在另一个线程上完成吗?
你能澄清一下我的理论错在哪里吗?
我相信locationManager
是在主线程上调用的,dispatch_sync
会导致主线程阻塞,直到block执行完,所以既然主线程会阻塞,什么也做不了,为什么不使用主线程来执行块?我认为这是对GCD的优化。
As an optimization, this function invokes the block on the current thread when possible.
您不能假设您提交给 dispatch_queue 的块将在任何线程中执行,dispatch_queue 不附加到任何特定线程(主队列除外)。