Multithreading executing multiple tasks in parallel in swift ios

和自甴很熟 提交于 2019-12-08 01:57:03

问题


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

Concurrent Queue ---->

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

}

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.


回答1:


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.



来源:https://stackoverflow.com/questions/50042458/multithreading-executing-multiple-tasks-in-parallel-in-swift-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!