LoginSignup
0
1

More than 1 year has passed since last update.

【Swift】ループ内を並列処理する

Posted at

はじめに

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

参考記事

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1