多线程在Swift iOS中并行执行多个任务 [英] Multithreading executing multiple tasks in parallel in swift ios

查看:659
本文介绍了多线程在Swift iOS中并行执行多个任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道队列的创建并且能够执行单个任务,但是我如何并行执行多个任务.

I know creation of queues and able to execute single task but how can i execute multiple tasks in parallel.

并发队列---->

let concurrentQueue = DispatchQueue(label: "com.some.concurrentQueue", attributes: .concurrent)
concurrentQueue.async {
    //executable code

}

无优先级的BackgroundQueue默认--->

BackgroundQueue without priorities default--->

DispatchQueue.global().async {
    //executable code
}

具有优先级的背景队列---->

Backgroundqueue with priorities---->

DispatchQueue.global(qos: .userInitiated).async { //.userInteractive .background .default .unspecified
    //executable code
}

回到主队列---->

Getting back to the main Queue ---->

DispatchQueue.main.async {
     //executable code
}

所有操作都是异步的,但是如何一次执行多个方法,应该如何快速编写代码.

All are asynchronous but how can i execute multiple methods at a time how should i code in swift.

推荐答案

如果您有一个调用方法的for循环方法,并且想同时调用此方法,则只需使用以下方法即可:

If you have a for loop method that calls a method and you want to calls this methods concurrent, so just use this :

DispatchQueue.concurrentPerform(iterations: Int, execute: { (count) in
   doSomethingFor(count: count)
}

但是,如果您有一些要并发调用的个体方法,请执行以下操作:

But if you have some individuals methods that you want to call concurrent, just do like this:

let concurrentQueue = DispatchQueue(label: "com.some.concurrentQueue", attributes: .concurrent)

concurrentQueue.async {
    //executable code
    myFirstMethod()
}

concurrentQueue.async {
    //executable code
       mySecondMethod()
}

这种并发队列将自己并发地管理您的任务.

This way concurrentQueue, will manages your tasks concurrently itself.

这篇关于多线程在Swift iOS中并行执行多个任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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