티스토리 뷰

728x90
반응형
func test() async {
    await withTaskGroup(of: Int.self) { taskGroup in
        
        [3,1,2].forEach { i in
            taskGroup.addTask {
                print("시작 \(i)")
                try? await Task.sleep(for: .seconds(i))
                return i
            }
        }
        
        for await element in taskGroup {
            print("완료 \(element)")
        }
    }
    print("모두 완료")
}

Task {
    await test()
}

/*
 시작 3
 시작 1
 시작 2
 한번에 호출되고
 1초 후
 완료 1
 2초 후
 완료 2
 3초 후
 완료 3
 모두 완료
 */

 

 

 

 

func test2() async -> [Int] {
    await withTaskGroup(of: Int.self) { taskGroup in
        
        [3,1,2].forEach { i in
            taskGroup.addTask {
                try? await Task.sleep(for: .seconds(i))
                return i
            }
        }
        
        // TaskGroup 은 AsyncSequence 를 따르기 때문에 reduce 가능
        return await taskGroup
            .reduce(into: [Int](), { $0.append($1)} )
    }
}

Task {
    print(await test2())
    // 완료된 순서대로 [1, 2, 3] 반환
}

 

 

 

iOS

Swift

Xcode

AsyncSequence

withTaskGroup

withThrowingTaskGroup

async

await

loop

dispatchGroup

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함