Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Protocols, Categories and Blocks

Blocks and Grand Central Dispatch

Run code concurrently in Objective-C with Grand Central Dispatch - serial and concurrent queues, dispatch_async, the main queue, groups, barriers, once, plus weak-self in async blocks.

Blocks are not just for sorting. Their biggest job is to describe work to be done later or elsewhere. Grand Central Dispatch (GCD) is the system library (libdispatch) that accepts blocks and runs them on managed threads. Instead of creating threads yourself, you put blocks on queues, and the system decides which thread runs them and how many to run at once.

GCD is a C API (dispatch_*), it works with any block, and it underlies NSOperationQueue, NSURLSession and much of UIKit's background work.

Queues

A queue is a FIFO list of blocks. There are two kinds:

  • Serial queue: runs one block at a time, in order. Perfect for protecting shared state without locks.
  • Concurrent queue: starts blocks in order but may run several at once.
OBJECTIVEC
dispatch_queue_t serial = dispatch_queue_create("com.example.accounts", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t concurrent = dispatch_queue_create("com.example.work", DISPATCH_QUEUE_CONCURRENT);

dispatch_queue_t main = dispatch_get_main_queue();                                    // serial, main thread
dispatch_queue_t global = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);    // shared concurrent

The main queue runs on the main thread, where all UI work must happen.

dispatch_async and dispatch_sync

OBJECTIVEC
dispatch_async(global, ^{
    NSData *data = [NSData dataWithContentsOfURL:url];       // slow work off the main thread
    UIImage *image = [UIImage imageWithData:data];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageView.image = image;                        // update UI on the main thread
    });
});

dispatch_async returns immediately and runs the block later. dispatch_sync waits for the block to finish. Be careful: calling dispatch_sync on the queue you are already running on deadlocks, for example dispatch_sync(dispatch_get_main_queue(), ...) from the main thread.

Dispatch groups

A group waits for several independent tasks:

OBJECTIVEC
dispatch_group_t group = dispatch_group_create();

for (NSURL *url in urls) {
    dispatch_group_async(group, global, ^{
        [self download:url];
    });
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    NSLog(@"all downloads finished");
});

When your tasks are themselves asynchronous, use dispatch_group_enter(group) before starting and dispatch_group_leave(group) in the completion handler.

Protecting shared data

A serial queue turns a shared variable into a safe one: every access is sent to the same queue, so accesses never overlap.

OBJECTIVEC
- (void)deposit:(double)amount {
    dispatch_async(self.accountQueue, ^{
        self.balance += amount;
    });
}

For a read-mostly resource, use a concurrent queue with a barrier: reads run in parallel, but a barrier write waits for earlier blocks and runs alone.

OBJECTIVEC
dispatch_sync(self.queue, ^{ result = self.cache[key]; });                  // concurrent read
dispatch_barrier_async(self.queue, ^{ self.cache[key] = value; });           // exclusive write

dispatch_once and dispatch_after

OBJECTIVEC
+ (instancetype)sharedInstance {
    static Config *shared;
    static dispatch_once_t once;
    dispatch_once(&once, ^{ shared = [[Config alloc] init]; });   // runs exactly once, thread-safe
    return shared;
}

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
               dispatch_get_main_queue(), ^{ [self hideBanner]; });

Blocks, self and cycles in async code

Async blocks capture self, which keeps the object alive until the block finishes. Usually that is fine, since the block is not stored by self. A cycle arises when self stores the block (a completion handler property). Use the weak-strong dance there, and also when you do not want to extend the object's lifetime for a long-running task.

OBJECTIVEC
__weak typeof(self) weakSelf = self;
dispatch_async(global, ^{
    NSString *result = [self expensiveWork];       // fine: self is kept alive until the block ends
    dispatch_async(dispatch_get_main_queue(), ^{
        typeof(self) strongSelf = weakSelf;
        if (strongSelf) strongSelf.label.text = result;   // skip the update if self is gone
    });
});

What a queue is: a model

You cannot call GCD from our runner, but a serial queue is just a first-in first-out list of work items with a loop that runs them. The stand-in below enqueues "blocks" (function pointer plus context) and drains them in order, then models a group with a counter and a completion callback.

C Stand-in: a serial queue and a dispatch group

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Real concurrency, safely: a counter

Real GCD would run on several threads. The following uses POSIX threads (which Piston supports) to show why shared state needs protection: four threads increment a counter with a mutex, which is the role a serial queue plays in GCD.

C Stand-in: protecting shared state (mutex = serial queue)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rules of thumb

  • Do all UI work on the main queue; do slow work elsewhere.
  • Prefer a private serial queue over locks for shared state.
  • Never dispatch_sync onto the queue you are already on.
  • Use groups to wait for several tasks, and dispatch_once for singletons.
  • For cancellation, dependencies and priorities, NSOperationQueue gives a higher-level API.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which queue must UI updates run on?

    UI frameworks are only safe on the main thread, which the main queue uses.
  2. 2. What is a deadlock caused by dispatch_sync(dispatch_get_main_queue(), ...) on the main thread?

    The main queue is serial and busy running the caller, so the sync block can never start.
  3. 3. What does dispatch_group_notify do?

    It schedules a block to run when the group's work has finished, without blocking.
  4. 4. Which tool lets reads run in parallel but writes run alone?

    dispatch_barrier_async waits for running blocks, runs exclusively, then lets the queue continue.

Summary

  • GCD runs blocks on queues; serial queues run one at a time, concurrent queues many.
  • dispatch_async returns immediately; dispatch_sync waits and can deadlock.
  • Groups wait for many tasks, barriers protect shared data, dispatch_once builds singletons.
  • Use weak-strong capture when a stored block would otherwise create a cycle.

Next: NSString and NSMutableString