관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - Swift] GCD(Grand Central Dispatch), DispatchQueue 본문

iOS 응용 (swift)

[iOS - Swift] GCD(Grand Central Dispatch), DispatchQueue

jake-kim 2020. 5. 20. 18:10

1. GCD

- Grand Central Dispatch API == GCD

* Dispatch : 출격, 배포

  GCD란 아래와 같은 기능을 쉽게 접근하여 일을 처리하는 API

Thread 갯수 Multi, Single
코어 갯수 멀티, 싱글
동기화 sync, async

2. DispatchQueue

- 큐에 담긴 각 아이템은 스레드 풀에 의해 처리됨

 

1)  main : Main Thread에서 처리되는 Serial queue (모든 UI작업은 Main Queue에서 수행되어야 함)

     global : 전체 시스템에 공유되는 concurrent queue

     custom : serial queue를 만들고 싶을 때 사용, global queue에서 실행

 

2) Serial 이전 작업이 끝나면 다음 작업이 순차적으로 진행

     Concurrent 병렬형태로 진행

 

3) sync : queue에 집어넣은 데이터들이 끝날 때 까지 코드진행 멈춤

     async : queue에 집어넣은 데이터들이 끝나지 않아도 코드진행 

 

ex)

DispatchQueue.main.async { } // main, async
DispatchQueue.global().sync { } // global, sync
DispatchQueue(label: "myQueue").async { } // serial, custom

// cuncurrent
DispatchQueue(label: "myQueue"), qos: .default, attributes: .concurrent, autoreleaseFrequencyL .inherit, target: nil).async { }

 

4) asyncAfter

시간을 주고 그 시간 후에 해당 작업을 하라는 의미

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { }

 

3. QoS(Quality of Service)

- 작업시 중요도의 우선순위에 따라 처리하는데, 이 중요도를 미리 정의한 개념이 QoS

- 어떤 작업을 Multi-threading으로 concurrent하게 처리하고자 할 때 사용

 

중요도 순으로 보면,

 

1) userInteractive

 유저 입장에서 가장 빠른 결과를 기대 : 유저가 버튼을 tap할 시 바로 작동, global queue이지만 main thread에서 실행

 

2) userInitiated

 유저 입장에서 조금 빠른 결과를 기대 : Async하게 처리

 

3) Default

background에서 실행 

 

4) utility

 유저 입장에서 기다리는 정도의 기대 : 계산, I/O, N/W

 

5) background

 유저 입장에서 실행되는지 몰라도 되는 정도의 바로 필요하지 않은 기대

 

ex)

DispatchQueue.global(qos: .userInteractive).async {
	let img = self.getImg()
            
	// UI관련 작업이므로 main queue에서
	DispatchQueue.main.async{
		self.imgView.image = img
	}     
 
}

 

* 참조

- developer.apple.com/documentation/dispatch

- www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2

 

* GCD에 대한 자세한 내용 : ios-development.tistory.com/138

 

[iOS - Swift] GCD(Grand Central Dispatch)

1. Concurrency "time-slicing" : iOS에서 각 쓰레드는 병렬적으로 동시에 실행 가능 single core device에서는 위 그림과 같이 Thread하나로 "context switch"를 하면서 동작 multicore device에서는 위 그림과..

ios-development.tistory.com

 

Comments