Swift - GCD(3)

Jenny·2021년 11월 16일
1
  • GCD : 디스패치 큐
  • Operation : 오퍼레이션 큐

- 디스패치 큐(GCD)

디스패치 큐의 종류는 크게 (글로벌)메인,글로벌,프라이빗(커스텀)큐가 있습니다.

Main Queue


//MARK: - Main Queue
DispatchQueue.main
  • 유일하게 한개만 존재(Main Thread에서 동작),Main Thread -> Thread 1
  • Serial(직렬) Queue
  • UI 처리를 담당

실행 코드


DispatchQueue.main.sync {...} // Error 사용불가
DispatchQueue.main.async {...} // 비동기적으로 Main Thread(Thread 1)으로 보냄
DisoatchQueue.main.asyncAfter(now() + 2) {...} // 지금으로 부터 2초 후에 비동기적으로 Main thread에 호출

Global Queue

  • Qos따른 6종류로 우선순위를 줄수 있음
  • Concurrent(동시) Queue : 여러개의 쓰레드로 분산 처리 함

서비스 품질 Qos(Quality of Service)

  • 중요한 순으로 서비스 품질(Qos)를 준다.
  • 종류 : userInteractive,userInitiated,default,utility,background,unspecified

실행 코드

// MARK: UI업데이트,애니메이션 등에 사용 (즉시)
DispatchQueue.global(qos: .userInteractive)

// MARK: 비동기적으로 처리된 작업 : 앱 내에서 pdf 파일을 여는 작업 (몇 초) 
DispatchQueue.global(qos: .userInitiated)

// MARK: 디폴트 
Dispatchqueue.global()

// MARK: Networking, Progress Indicator와 함께 길게 실행하는 작업 (몇초에서 몇분)
DispatchQueue.global(qos: .utility)

//MARK: 시간이 안 중요한 작업, 데이터 미리가져오기, 데이터 베이스 유지 (몇분 이상)
DispatchQueue.global(qos: .background)

//MARK: legacy API
DispatchQueue.global(qos: .unspecified)

Private Queue(커스텀 큐)

Dispatchqueue(label: )
Dispatchqueue(label: , attributes:)
  • 디폴트(Serial) Queue (Concurrent)로 설정 가능
  • Qos (설정 가능) : 설정 하지 않아도 OS에서 알아서 Qos를 추론한다.
  • label을 설정하여 Custom Queue를 설정할수 있다.

실행 코드

let customQueue = DispatchQueue(label:"SerialQueue")
let customConcurrentQueue = DispatchQueue(label: "ConcurrentQueue", attributes: .concurrent)
GCD 주의사항
- UI 작업은 항상 Main Thread에서 작업을 해야한다 DispatchQueue.main
- Main Thread에서 작업을 할때 Sync로 보내는 것을 해서는 안된다. Sync로 보내면 실행중이던 쓰레드는 block 상태가 된다.

인프런 - iOS Concurrency(동시성) 프로그래밍, 동기 비동기 처리 그리고 GCD/Operation - 디스패치큐와 오퍼레이션큐의 이해

profile
"Jenny 있게 iOS 개발을 하며 대체 불가능한 인재가 되자"

0개의 댓글