简体   繁体   English

iOS Swift中的多线程

[英]MultiThreading in IOS Swift

I am trying to run two threads in parallel. 我试图并行运行两个线程。 But unfortunately , it sometime works sometime not. 但不幸的是,它有时无法正常工作。 Here is my code 这是我的代码

 let firstQueue = DispatchQueue(label: "queue1", qos: DispatchQoS.userInitiated)
 let secondQueue = DispatchQueue(label: "queue2", qos: DispatchQoS.userInitiated)
//let firstQueue = DispatchQueue(label: "queue1", qos: DispatchQoS.default , attributes: .concurrent)

    firstQueue.async {
        for i in 0..<10 {
            print("🔷", i)
        }
    }


    secondQueue.async {
        for i in 20..<30 {
            print("⚪️", i)
        }
    }

I have tried different everything but not achieve perfect parallelism. 我尝试了所有不同的方法,但没有达到完美的并行性。 First Time Output: 0 ⚪️ 20 🔷 1 ⚪️ 21 🔷 2 ⚪️ 22 🔷 3 ⚪️ 23 🔷 4 ⚪️ 24 🔷 5 ⚪️ 25 🔷 6 ⚪️ 26 🔷 7 ⚪️ 27 🔷 8 ⚪️ 28 🔷 9 ⚪️ 29 第一次输出: 0 ⚪️ 20 🔷 1 ⚪️ 21 🔷 2 ⚪️ 22 🔷 3 ⚪️ 23 🔷 4 ⚪️ 24 🔷 5 ⚪️ 25 🔷 6 ⚪️ 26 🔷 7 ⚪️ 27 🔷 8 ⚪️ 28 🔷 9 ⚪️ 29

SecondTime Output : SecondTime输出:

🔷 0 🔷 1 🔷 2 🔷 3 🔷 4 🔷 5 🔷 6 🔷 7 🔷 8 🔷 9 ⚪️ 20 ⚪️ 21 ⚪️ 22 ⚪️ 23 ⚪️ 24 ⚪️ 25 ⚪️ 26 ⚪️ 27 ⚪️ 28 ⚪️ 29 🔷0🔷1🔷2🔷3🔷4🔷5🔷6🔷7🔷8🔷9⚪️20⚪️21⚪️22⚪️23⚪️24⚪️25⚪️26⚪️27⚪️28⚪️29

Your code works well, but the thing you should know is that, you haven't any choice to decide which part of your code execute first, and since your code is just printing a character and its a light job to do for cpu you see some times your characters printing ordered and some times unordered. 您的代码运行良好,但是您应该知道的是,您没有选择决定代码的哪个部分首先执行的选择,并且由于您的代码只是打印一个字符并且为cpu做的轻松工作,因此您会看到有时您的字符打印是有序的,有时是无序的。 Try to give some more heavy job to cpu and then see the results! 尝试给CPU分配更多的工作,然后查看结果!

You can use DispatchGroup , also you should read more about GCD, the code below work as expected and it will fix your issue 您可以使用DispatchGroup ,也应该阅读有关GCD的更多信息,下面的代码按预期工作,它将解决您的问题

let dispatchGroup = DispatchGroup()
let firstQueue = DispatchQueue(label: "queue1", qos: DispatchQoS.userInitiated)
let secondQueue = DispatchQueue(label: "queue2", qos: DispatchQoS.userInitiated)

firstQueue.async(group: dispatchGroup) {
    for i in 0..<10 {
        print("🔷", i)
    }
    dispatchGroup.leave()
}

secondQueue.async(group: dispatchGroup) {
    dispatchGroup.wait()
    for i in 20..<30 {
        print("⚪️", i)
    }
}

the output always will be like this 🔷 0 🔷 1 🔷 2 🔷 3 🔷 4 🔷 5 🔷 6 🔷 7 🔷 8 🔷 9 ⚪️ 20 ⚪️ 21 ⚪️ 22 ⚪️ 23 ⚪️ 24 ⚪️ 25 ⚪️ 26 ⚪️ 27 ⚪️ 28 ⚪️ 29 输出总是像这样🔷0🔷1🔷2🔷3🔷4🔷5🔷6🔷7🔷8🔷9⚪️20⚪️21⚪️22⚪️23⚪️24⚪️25⚪️26⚪️27⚪️28⚪️29

The point of multithreading is that operations will be done parallel and independent from one another. 多线程的要点是,操作将并行且彼此独立地完成。 That does not guaranty any order at all, there is no synchronization, no nothing. 那根本不保证任何顺序,没有同步,什么也没有。 If you need to have things synchronized then you will need to use a single thread or use a third thread that dispatches work: 如果需要使事物同步,则将需要使用单个线程或使用第三个线程来分派工作:

func foo() {
    let firstQueue = DispatchQueue(label: "queue1")
    let secondQueue = DispatchQueue(label: "queue2")

    let mainQueue = DispatchQueue(label: "queueMain")

    var firstQueueOperationsCount: Int = 10
    var secondQueueOperationsCount: Int = 10

    func performOperations() {
        guard max(firstQueueOperationsCount, secondQueueOperationsCount) > 0 else {
            return
        }
        mainQueue.async {
            if firstQueueOperationsCount > secondQueueOperationsCount {
               firstQueueOperationsCount -= 1
                firstQueue.async {
                    print("🔷")
                    performOperations()
                }
            } else {
                secondQueueOperationsCount -= 1
                secondQueue.async {
                    print("⚪️")
                    performOperations()
                }
            }
        }
    }

    performOperations()
}

There are many ways on how to serialize tasks dispatched on multiple threads and this being just one of them. 有很多方法可以序列化在多个线程上分派的任务,这只是其中之一。 You might try searching/reading toward that direction but just be clear: What you seem to expect from multithreading is NOT WHAT MULTITHREADING IS. 您可以尝试朝这个方向搜索/阅读,但要清楚一点:您似乎对多线程所期望的不是“多线程”。 It does not work this way and it does not supposed to work this way. 它不能以这种方式工作,也不应该以这种方式工作。 How they do work is how we want it to work. 他们如何工作是我们希望它如何工作。

If you have a more specific situation I am sure community here may help you identify a good approach to solve it. 如果您遇到的情况更具体,我相信这里的社区可以帮助您找到解决问题的好方法。 But from what you have written the result is not multithreading but: 但是从您编写的内容来看,结果不是多线程而是:

for i in 0..<10 {
    print("🔷")
    print("⚪️")
}

It might be dispatched on another thread but that really makes no difference. 它可能在另一个线程上分派,但实际上没有什么区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM