GCD 主线程崩溃问题(需要解释)?
GCD Main Thread Crash Issue (Explanation Needed)?
为什么这段代码会导致崩溃?
DispatchQueue.main.sync {
// Operation To Perform
}
为什么我们必须这样写:-
DispatchQueue.global().async(execute: {
print("test")
DispatchQueue.main.sync{
print("main thread")
}
})
当我们在 CellForRowAt 或任何其他方法中编写代码时,它在哪个线程中进入主线程或全局线程以同步或异步方式工作?
为什么崩溃简而言之
DispatchQueue.main.sync {
// Operation To Perform
}
calling sync and targeting current queue is a deadlock (calling queue waits for the sync block to finish, but it does not start because target queue (same) is busy waiting for the sync call to finish) and thats probably why the crash.
对于第二个块:您正在创建全局队列,然后您正在获取主队列,因此现在没有死锁
如果你曾经使用过semaphore
,如果你不注意也会有同样的问题
它有两个方法 wait
和 signal
与 wait
如果你阻止 main thread
那么你的代码将永远不会执行。
希望对您有所帮助
根据 Apple,尝试在主队列上同步执行工作项会导致 死锁。
所以写 DispatchQueue.main.sync {}
会导致死锁情况,因为 app 执行的所有 UI 操作都在主队列 上执行,除非我们手动切换一些任务在后台队列中。这也回答了关于在哪个线程上调用 CellForRowAt 的问题。所有与UI操作或UIkit相关的方法都从主线程
调用
同步执行任务意味着阻塞线程直到任务未完成,在这种情况下,您试图阻塞系统/应用程序已经在其上执行某些任务并可能导致死锁的主线程。完全不建议阻塞主线程,这就是为什么我们需要 异步切换到后台线程 这样主线程就不会被阻塞。
要阅读更多内容,您可以访问以下内容link:
https://developer.apple.com/documentation/dispatch
DispatchQueue.main.sync {
// Operation To Perform
}
在您已经在的串行队列(如 main
)上调用同步将导致死锁。第一个进程无法完成,因为它正在等待第二个进程完成,第二个进程无法完成,因为它正在等待第一个进程完成等等。
DispatchQueue.global().async(execute: {
print("test")
DispatchQueue.main.sync{
print("main thread")
}
})
在将任务移动到 global()
队列时,从这里在主线程上调用 sync
是有效的。
raywenderlich.com 上有一个很棒的 2 部分 GCD 教程,我鼓励您阅读 https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1。
为什么这段代码会导致崩溃?
DispatchQueue.main.sync {
// Operation To Perform
}
为什么我们必须这样写:-
DispatchQueue.global().async(execute: {
print("test")
DispatchQueue.main.sync{
print("main thread")
}
})
当我们在 CellForRowAt 或任何其他方法中编写代码时,它在哪个线程中进入主线程或全局线程以同步或异步方式工作?
为什么崩溃简而言之
DispatchQueue.main.sync {
// Operation To Perform
}
calling sync and targeting current queue is a deadlock (calling queue waits for the sync block to finish, but it does not start because target queue (same) is busy waiting for the sync call to finish) and thats probably why the crash.
对于第二个块:您正在创建全局队列,然后您正在获取主队列,因此现在没有死锁
如果你曾经使用过semaphore
,如果你不注意也会有同样的问题
它有两个方法 wait
和 signal
与 wait
如果你阻止 main thread
那么你的代码将永远不会执行。
希望对您有所帮助
根据 Apple,尝试在主队列上同步执行工作项会导致 死锁。
所以写 DispatchQueue.main.sync {}
会导致死锁情况,因为 app 执行的所有 UI 操作都在主队列 上执行,除非我们手动切换一些任务在后台队列中。这也回答了关于在哪个线程上调用 CellForRowAt 的问题。所有与UI操作或UIkit相关的方法都从主线程
同步执行任务意味着阻塞线程直到任务未完成,在这种情况下,您试图阻塞系统/应用程序已经在其上执行某些任务并可能导致死锁的主线程。完全不建议阻塞主线程,这就是为什么我们需要 异步切换到后台线程 这样主线程就不会被阻塞。
要阅读更多内容,您可以访问以下内容link: https://developer.apple.com/documentation/dispatch
DispatchQueue.main.sync {
// Operation To Perform
}
在您已经在的串行队列(如 main
)上调用同步将导致死锁。第一个进程无法完成,因为它正在等待第二个进程完成,第二个进程无法完成,因为它正在等待第一个进程完成等等。
DispatchQueue.global().async(execute: {
print("test")
DispatchQueue.main.sync{
print("main thread")
}
})
在将任务移动到 global()
队列时,从这里在主线程上调用 sync
是有效的。
raywenderlich.com 上有一个很棒的 2 部分 GCD 教程,我鼓励您阅读 https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1。