在swift 3中发布GCD中的并发队列

时间:2016-12-26 09:24:27

标签: swift3 grand-central-dispatch

我在swift 3中遇到GCD问题 我创建并发队列,我在此队列中传递函数,此函数调用另一个函数 我需要打印每次通话的已用时间 但我认为在我的代码下面的并发队列中实现了实现:

// peform task with the concurrent queue
class DoCalculations{
    func doCalc() {
        let x = 100
        let y = x * x
        _ = y / x

    }

    func performCalculation(itretion:Int,tag:String) {
        let start = CFAbsoluteTimeGetCurrent()

        for _ in 0..<itretion {
            self.doCalc()
        }

        let end = CFAbsoluteTimeGetCurrent()

        print("tag :\(tag) : \(end - start)")

    }
}


let calc = DoCalculations()

let cQueue = DispatchQueue(label: "com.myCompany", attributes: .concurrent)

cQueue.async {
    calc.performCalculation(itretion: 1000000, tag: "sync1")
}
cQueue.async {
    calc.performCalculation(itretion: 1000, tag: "sync2")
}

cQueue.async {
    calc.performCalculation(itretion: 100000, tag: "sync3")
}

//打印功能不是Excuted 请解决这个问题

1 个答案:

答案 0 :(得分:1)

如果你在游乐场上这样做,你想表明“在游乐场的顶级代码结束后,应该继续执行”。您可以使用needsIndefiniteExecution执行此操作:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

正如needsIndefiniteExecution的文档所说:

  

一个布尔值,指示是否启用了无限期执行。   默认情况下,执行所有顶级代码,然后终止执行。使用异步代码时,启用无限期执行以允许在达到操场的顶级代码结束后继续执行。反过来,这为线程和回调提供了执行的时间。

     

即使启用了无限期执行,编辑游乐场也会自动停止执行。

     

needsIndefiniteExecution设置为true以在顶级代码结束后继续执行。将其设置为false以在此时停止执行。   默认值为false。当liveView设置为非nil值时,它设置为true。

相关问题