Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios DispatchSemaphore导致应用程序冻结,如何解决_Ios_Swift_Iphone_Grand Central Dispatch - Fatal编程技术网

Ios DispatchSemaphore导致应用程序冻结,如何解决

Ios DispatchSemaphore导致应用程序冻结,如何解决,ios,swift,iphone,grand-central-dispatch,Ios,Swift,Iphone,Grand Central Dispatch,当我运行代码时,我点击iphone主页按钮,然后重新打开我的应用程序,我的应用程序被冻结了。我感到不确定,为什么 let queue = DispatchQueue(label: "com.aiswei.asw.monitior.search",qos: .default, attributes: .concurrent) let semaphore = DispatchSemaphore(value: 30) let minX = 2

当我运行代码时,我点击iphone主页按钮,然后重新打开我的应用程序,我的应用程序被冻结了。我感到不确定,为什么

let queue = DispatchQueue(label: "com.aiswei.asw.monitior.search",qos: .default, attributes: .concurrent)
        let semaphore = DispatchSemaphore(value: 30)
        let minX = 2
        let maxX = 254
        self.index = minX
self.index = minX
        let count = maxX - minX + 1
        let lock = NSLock()
        for i in minX...maxX {
            queue.async {
                semaphore.wait()
                lock.lock()
                // request some server api  result
                 NetCenter.requestAPi { (result) in
                    semaphore.signal()
                }
            
                lock.unlock()
              
            }
        
        }


我希望这将尝试创建超过250个线程,而这是您不想做的。这就是说,我的怀疑是,真正的问题在于走在前台是在别处;可能在网络中心。您可能正在死锁主队列(特别是如果NetCenter是以相同的样式编写的)

与启动大量DispatchWorkItem然后阻塞它们不同,您可以通过在串行队列上使用单个DispatchWorkItem和您的信号量来实现相同的目标。串行队列将不再需要锁。这一次序列化30个操作,我想这是您想要的

    let queue = DispatchQueue(label: "com.aiswei.asw.monitior.search")
    let semaphore = DispatchSemaphore(value: 30)

    queue.async {
        let minX = 2
        let maxX = 254
        for _ in minX...maxX {
            semaphore.wait()
            NetCenter.requestAPi { (result) in
                semaphore.signal()
            }
        }
    }
}

这里我假设
requestAPi
是一个异步方法,它将在
queue
以外的队列上调度其完成处理程序。(如果NetCenter使用与此函数相同的队列,那么肯定会死锁。)

我有254个任务,我只需要同时执行少于30个任务。因此我使用DispatchSemaphore来限制。NetCenter.requestApi包含其他线程任务。那么上面的代码应该正是您需要的。谢谢@Rob Napier,但当队列执行时。我单击“主页”按钮。然后我重新打开我的应用。我的应用被冻结。这是一个信号量错误吗?正如我所说,这个错误可能来自其他地方(或者作为此代码和其他代码之间的交互)。我怀疑您的NetCenter代码或应用程序代理代码。您肯定希望从应用程序委托中的DIDENTERFORMENT代码开始。如果答案不明显,则继续删除代码,直到问题消失,这将告诉您问题发生的位置。您发布的代码是错误的并发代码,可能会由于耗尽线程池而导致锁定,但实际问题可能在其他地方。thanks@Rob纳皮尔,我做了,你解释了什么。当我检查我的代码时,我发现我的代码与你的代码有些不同。我将uux的
放在minX…maxX
的'queue.async{}'外。我想知道为什么我的代码工作不好。