DispatchGroup会永远等待吗?

我想知道以下场景。

我有一个DispatchGroup内部函数。现在我正在后台线程上进入该组并调用wait().

func test() {
   let group = DispatchGroup()
   
   DispatchQueue.global().async {
      group.enter()
      group.wait()
   }
}

我的问题是,在主线程离开函数后,该组是否会永远等待或被释放?

我不确定是否有任何引用或捕获。我会非常感谢一些解释,这个话题让我有点困惑。

先感谢您!

回答

是的,它将永远等待。

group被捕获,因此不会被释放。而且,很明显,你最终会锁定那个特定的工作线程。由于工作线程非常有限,这比DispatchGroup.

如果您希望它超时,请使用wait(timeout:).

  • Just a small addition to the otherwise great answer: for this exact reason, it's usually better to use `DispatchGroup.notify(queue:execute)`, which doesn't block the queue, but waits asynchronously.

以上是DispatchGroup会永远等待吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>