1

我正在尝试并行运行两个线程。但不幸的是,它有时工作有时不工作。这是我的代码

 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)
        }
    }

我尝试了不同的一切,但没有达到完美的并行性。第一次输出:0 ⚪️ 20 1 ⚪️ 21 2 ⚪️ 22 3 ⚪️ 23 4 ⚪️ 24 5 ⚪️ 25 6 ⚪️ 26 7 ⚪️ 27 8 ⚪️ 28 9 ⚪️ 29

第二次输出:

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

4

3 回答 3

-1

你的代码运行良好,但你应该知道的是,你没有任何选择来决定你的代码的哪一部分首先执行,因为你的代码只是打印一个字符并且它对你看到的 cpu 来说是一项轻松的工作有时您的字符打印是有序的,有时是无序的。尝试给cpu一些更繁重的工作,然后看看结果!

于 2018-04-26T09:21:06.750 回答
-1

您可以使用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)
    }
}

输出总是这样 0 1 2 3 4 5 6 7 8 9 ⚪️ 20 ⚪️ 21 ⚪️ 22 ⚪️ 23 ⚪️ 24 ⚪️ 25 ⚪️ 26 ⚪️ 27 ⚪️ 28 ⚪️ 29

于 2018-04-26T09:27:46.073 回答
-1

多线程的要点是操作将并行完成并且彼此独立。那根本不保证任何顺序,没有同步,什么都没有。如果您需要同步事情,那么您将需要使用单个线程或使用分派工作的第三个线程:

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()
}

关于如何序列化在多个线程上分派的任务有很多方法,这只是其中之一。您可能会尝试朝那个方向搜索/阅读,但要清楚:您似乎对多线程的期望不是多线程是什么。它不以这种方式工作,也不应该以这种方式工作。他们如何工作就是我们希望它如何工作。

如果您有更具体的情况,我相信这里的社区可以帮助您找到解决问题的好方法。但从你写的结果来看,结果不是多线程,而是:

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

它可能会在另一个线程上分派,但这确实没有区别。

于 2018-04-26T10:05:57.560 回答