iOS, GCD(Grand Central Dispatch)1

iDO·2021년 11월 11일
0

iOS

목록 보기
3/8
post-thumbnail

🧐 네트워킹, 비동기 작업을 위해서라면 알아야하는 GCD에 대해서 알아보겠습니다.

🍁 DispatchQueue

DispatchQueue는 작업을 실행하는 FIFO Queue입니다. DispatchQueue는 작업을 serially(순차적) 또는 concurrently(동시적)으로 실행합니다. DispatchQueue에 제출된 작업은 Thread 에서 실행됩니다.

🍁 Main Queue

현재 프로세스의 기본 스레드와 연결된 디스패치 큐입니다. serial 큐로 Main thread 동작합니다.

DispatchQueue.main.async {
// UI 관련된 요소 처리
}

🍁 Global Queue

지정된 서비스 품질 클래스(qos)가 있는 큐로 반환합니다. default는 concurrent queue 입니다.

DispatchQueue.global().async {
// 글로벌 큐에서 비동기 작업 실행
}
DipatchQueue.global(qos: .background).async {
// qos를 설정하여 우선수위를 설정할 수 있습니다.
}
QoS

상단이 중요도가 높고 빨리 실행시킵니다..
case userInteractive:
가장 급한 일 -> 가장 빨리 실행 시킴
애니메이션, 이벤트 처리 또는 앱의 사용자 인터페이스 업데이트와 같은 사용자와 상호작용.
case userInitiated:
사용자가 즉시 필요하지만, 비동기적으로 처리된 작업
case default:
기본
case utility:
사용자가 적극적으로 추적하지 않는 작업. 조금 무거운 작업(네트워크, 네트워킹 작업)
case background:
당장 필요하지 않은 작업(위치 업데이트, 다운 등)
case unspecified:
부재(사용한적이 없어 잘모르겠습니다.)

🍁 Custom Queue

커스텀으로 만든 큐, default는 serial queue입니다.

let serialQueue = DispatchQueue(label: "serial", qos: .background)
let concQueue = DispatchQueue(label: "concurrent", qos: .background, attributes: .concurrent)

🍁 Serial? Concurrent?

serial - 한개의 Thread에서 처리
concurrent - 여러개의 Thread에서 처리

🍁 Sync(동기)? / Async(비동기)?

sync - 작업이 끝나길 기다린다
async - 작업이 끝나길 기다리지 않는다.

🍁 ex.swift

DispatchQueue.global().async {
                guard let url = URL(string: "url") else { return } // Global 큐에서 비동기로 실행 (이미지를 가져오는동안 다른 작업을 실행가능하게 하기위해)
                guard let data = try? Data(contentsOf: url) else { return }
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    imageView.image = image
                } // 메인 큐로 전환하며 ui update
            }

🧐(아래 참고내용을 통해 더 자세한 정보를 확인할 수 있습니다!)
Apple Developer Documentation

profile
이곳은 저를 위한 iOS 설명서입니다.

0개의 댓글