Swift中的main.sync使DispatchQueue崩溃 [英] DispatchQueue crashing with main.sync in Swift

查看:233
本文介绍了Swift中的main.sync使DispatchQueue崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请向我解释为什么我会发生此崩溃?

Please explain to me why I am getting this crash?

线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

在此

DispatchQueue.main.sync { 打印(同步") }

DispatchQueue.main.sync { print("sync") }

这是我的代码.

    override func viewDidLoad() {
    super.viewDidLoad()


    print("Start")
    DispatchQueue.main.async {
        print("async")

    }
    DispatchQueue.main.sync {
        print("sync")
    }
    print("Finish")
}

推荐答案

从不在主队列上调用同步功能

如果在主队列上调用同步功能,它将阻塞该队列,并且该队列将等待任务完成,但是该任务将永远无法完成,因为由于以下原因它甚至无法启动队列已被阻塞.它称为死锁.

If you call the sync function on the main queue it will block the queue as well as the queue will be waiting for the task to be completed but the task will never be finished since it will not be even able to start due to the queue is already blocked. It is called deadlock.

如果两个(或有时更多)项目(大多数情况下是线程)陷入僵局,则它们全都陷入困境,彼此等待对方完成或执行其他操作,则被称为死锁.第一个无法完成,因为它正在等待第二个完成.但是第二个无法完成,因为它正在等待第一个完成.

Two (or sometimes more) items — in most cases, threads — are said to be deadlocked if they all get stuck waiting for each other to complete or perform another action. The first can’t finish because it’s waiting for the second to finish. But the second can’t finish because it’s waiting for the first to finish.

但是您需要小心.想象一下,如果您调用同步并定位您已经在运行的当前队列.这将导致死锁情况.

You need to be careful though. Imagine if you call sync and target the current queue you’re already running on. This will result in a deadlock situation.

使用同步功能来跟踪有调度障碍的工作,或者在需要等待操作完成之前,才可以使用闭包处理的数据.

Use sync to keep track of your work with dispatch barriers, or when you need to wait for the operation to finish before you can use the data processed by the closure.

何时使用同步?

当我们需要等到任务完成时. F.e.当我们确保某些函数/方法没有被双重调用时. F.e.我们进行了同步,并尝试防止重复调用它,直到完全完成为止. 当您需要等待在不同队列上完成的事情,然后才继续在当前队列上工作

When we need to wait until the task is finished. F.e. when we are making sure that some function/method is not double called. F.e. we have synchronization and trying to prevent it to be double called until it's completely finished. When you need to wait for something done on a DIFFERENT queue and only then continue working on your current queue

同步与异步

使用GCD,您可以同步或异步分派任务.

With GCD, you can dispatch a task either synchronously or asynchronously.

任务完成后,同步功能会将控制权返回给调用方.

A synchronous function returns control to the caller after the task is completed.

异步函数立即返回,命令任务完成但不等待它.因此,异步功能不会阻止当前执行线程继续进行下一个功能.

An asynchronous function returns immediately, ordering the task to be done but not waiting for it. Thus, an asynchronous function does not block the current thread of execution from proceeding on to the next function.

这篇关于Swift中的main.sync使DispatchQueue崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆