MAC:Concurrency
Concurrency is the notion of multiple things happening at the same time. With the proliferation of multicore CPUs and the realization that the number of cores in each processor will only increase, software developers need new ways to take advantage of them. Although operating systems like OS X and iOS are capable of running multiple programs in parallel, most of those programs run in the background and perform tasks that require little continuous processor time. It is the current foreground application that both captures the user’s attention and keeps the computer busy. If an application has a lot of work to do but keeps only a fraction of the available cores occupied, those extra processing resources are wasted.
Asynchronous Code Block
heavyOperatingMethod라는 메서드가 작업 시간이 오래 걸리지만 UI는 이 메서드가 리턴하는 값을 이용해야 한다. 하지만 heavyOperatingMethod의 응답을 기다리기에는 UI가 그냥 멈춰버리기 때문에 사용자에게서 불만이 생길 것 같다. 이 경우 heavyOperatingMethod를 비동기로 처리해보자. 아래 코드는 그 예제 코드이다.
// 내부블럭의 코드 실행에 영향을 받지 않고 바로 넘어간다.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
// 작업이 오래 걸리는 API를 호출
BOOL res = [self heavyOperatingMethod];
dispatch_async(dispatch_get_main_queue(), ^{
// 이 블럭은 위 작업이 완료되면 호출된다.
if (res) {
[self operationSucceed];
} else {
[self operationFailed];
}
});
});
위 코드 예제는 GCD(General Central Dispatch)라 불리우는 개념을 이용한 것으로 iOS 뿐만 아니라 OSX에서도 멀티프로세서를 효율적으로 사용하도록 하기 위해 지원하는 기능이다.
dispatch_async라는 함수를 이용한다. 여기서는 큐(Queue)를 두 가지 사용한다. 하나는 Global Queue 이고 다른 하나는 Main Queue이다. Global Queue는 백그라운드 프로세싱을 위한 것이라고 생각되고 Main Queue는 UI에서 사용하는 것이라고 생각된다.
Main Queue 부분의 dispatch async코드를 그냥 Global Queue로 빼서 사용해도 비동기적으로 동작하는데 무리는 없다. 하지만 이 경우 처리결과가 UI로 전달되는데 제법 시간이 오래 걸릴 수도 있다. 처음 쓸 때는 안쪽 dispatch_async 코드를 빼 먹어서 왜 UI가 응답을 늦게 받는지 고민했었는데 굉장히 중요한 부분이다.