はじめに
DispatchQueueを使用しての並列処理の例はいくつも出てきますが、Swift Concurrencyでの並列処理の例はなかなか見つからなかったので記事にしておきます。
DispatchQueue
func sample1() {
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label: "sample", attributes: .concurrent)
for i in 0..<10 {
dispatchQueue.async(group: dispatchGroup) {
Thread.sleep(forTimeInterval: TimeInterval(Int.random(in: 1...10)))
print(i)
}
Thread.sleep(forTimeInterval: 1.0)
}
}
Swift Concurrency
func sample2() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
for i in 0..<10 {
group.addTask {
try await Task.sleep(until: .now + .seconds(Int.random(in: 1...10)), clock: .suspending)
print(i)
}
try await Task.sleep(until: .now + .seconds(1.0), clock: .suspending)
}
}
}
参考記事