Skip to content
Search

MAC:Concurrency

lastmod 2018-08-17created 2014-03-045 edits

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

A method called heavyOperatingMethod takes a long time to run, but the UI has to use the value this method returns. Waiting for heavyOperatingMethod's response would simply freeze the UI, which is likely to annoy users. In this case, let's handle heavyOperatingMethod asynchronously. The code below is an example.

// 내부블럭의 코드 실행에 영향을 받지 않고 바로 넘어간다.
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];
        }
    });
});

The code example above uses a concept called GCD (General Central Dispatch), a feature supported not only on iOS but also on OSX to make efficient use of multiple processors.

It uses a function called dispatch_async. Two queues are used here: one is the Global Queue and the other is the Main Queue. The Global Queue seems to be for background processing, and the Main Queue seems to be what the UI uses.

Moving the dispatch async code in the Main Queue part out into the Global Queue still works asynchronously without problems. In that case, however, it can take quite a long time for the result to reach the UI. When I first used it, I left out the inner dispatch_async code and puzzled over why the UI was getting its response so late, so this is a very important part.

Favorite site