gpt4 book ai didi

swift - For 循环中的 DispatchGroup

转载 作者:搜寻专家 更新时间:2023-11-01 06:01:48 24 4
gpt4 key购买 nike

因此,我花了一些时间尝试让 DispatchGroup 在长时间的异步操作完成之前阻止 for 循环迭代。我发现的大多数示例都相当简单明了,但我似乎无法让我的简单测试用例按预期工作。

let group = DispatchGroup()

for i in 1...3 {
group.enter()
print("INDEX \(i)")
asynchronousOperation(index: i, completion: {
print("HELLO \(i)")
self.group.leave()

})
print("OUTSIDE \(i)")
}


func asynchronousOperation(index: Int, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+5) {
print("DONE \(index)")
completion()

}
}

打印结束

START
INDEX 1
OUTSIDE 1
INDEX 2
OUTSIDE 2
INDEX 3
OUTSIDE 3
DONE 1
HELLO 1
DONE 2
HELLO 2
DONE 3
HELLO 3

我希望它打印出更像的东西

START
INDEX 1
OUTSIDE 1
HELLO 1
INDEX 2
OUTSIDE 2
HELLO 2
INDEX 3
OUTSIDE 3
HELLO 3

只要在 asynchronousOperation() 内部调用 group.leave() 之前,不会打印 OUTSIDE 之后的下一个“INDEX”

可能是一些简单的事情我误解了——有什么想法吗?

最佳答案

执行下面的代码以获得正确的输出:

for i in 1...3 {
let semaphore = DispatchSemaphore(value: 0) // create a semaphore with a value 0. signal() will make the value 1.
print("INDEX \(i)")
asynchronousOperation(index: i, completion: {
print("HELLO \(i)")
semaphore.signal() // once you make the signal(), then only next loop will get executed.
})
print("OUTSIDE \(i)")
semaphore.wait() // asking the semaphore to wait, till it gets the signal.
}

func asynchronousOperation(index: Int, completion: @escaping () -> ()) {
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()+5) {
print("DONE \(index)")
completion()
}
}

输出:

索引 1外面 1完成 1你好 1

索引 2外面2完成 2你好 2

索引 3外面3完成 3你好 3

关于swift - For 循环中的 DispatchGroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47735204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com