동시성 프로그래밍
Swift에는 이러한 동시성 프로그래밍을 가능캐 해주는 2가지 기능이 있다.
- Dispatch Queue
- Operation Queue
GCD(Grand Central Dispatch)
Dispatch Queue는 FIFO Queue형태로 작업을 순서대로 전달받는다.
Serial / Concurrent
Serial
- 이전 작업이 끝나면 다음 작업을 시작하는 직렬 형태
- 아무런 설정을 하지 않으면 Serial로 동작
Concurrent
Sync / Async
Sync
Async
Main / Global
Main
- Main Thread가 해당 작업을 맡음
- Default는 Serial로 동작하나 Concurrent로 변경 가능
Global
- Concurrent로 실행되나, QoS를 통해 우선순위를 정할 수 있음
Dispatch Group
Dispatch Queue로 처리된 모든 작업이 완료된 시점을 파악하기 위하여 사용한다.
- enter로 Group에 queue를 넣음
- leave로 해당 queue가 완료되었음 알려줌
- Group에 enter로 들어간 모든 queue가 leave하면 notify로 모든 작업이 수행됨을 알려줌
Dispatch WorkItem
- Dispatch Queue를 클로저 형태로 저장할 수 있다.
- cancel을 통해 작업을 취소할 수 있다.
- notify로 다음 Task를 지정할 수 있다.
let item = DispatchWorkItem {
print("123")
}
DispatchQueue.global().async(excute: item)
Dispatch Semaphore
동시 작업 개수를 제한한다.
임계구역에 들어갈 땐 wait(), 나올 땐 siginal()