首页 > 解决方案 > 如何在 Swift 中实现“无尽任务”

问题描述

我是 Swift 的新手,我没有太多的经验。问题是,当我添加以下代码时,我遇到了 CPU 使用率高的问题(Xcode 调试会话中超过 100% 的 cpu 使用率)。

为了实现无限工作线程,我使用了 GCD(许多文章中最推荐的方式),包括 while-loop 结构。

private let engineQueue = DispatchQueue(label: "engine queue", qos: .userInitiated)

public func startEngine() {
        engineQueue.async {
            while true {
                if (self.captureManager.isSessionRunning) {
                    guard let frame = self.captureManager.frameQueue.popFrame(),
                        let buf = frame.getYPlanar() else {
                            continue
                    }

                    // process a frame
                    self.engine.processNewFrame(buf: buf, width: Int32(frame.cols!), height: Int32(frame.rows!))
                }
            }
        }
    }

而且我注意到这是一种糟糕的做法(高 CPU 使用率),肯定有比这更好的方法。

所以问题是

  1. 在这种情况下我必须使用 GCD 而不是 Thread 吗?

  2. 为此工作的最佳方法是什么?

谢谢,

标签: swiftmultithreadinggrand-central-dispatch

解决方案


推荐阅读