Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Grand Central Dispatch

Rob Brown
December 08, 2011

Grand Central Dispatch

Grand Central Dispatch (GCD) and blocks are a great tool that makes multi-threading easy, efficient, and enjoyable.

Rob Brown

December 08, 2011
Tweet

More Decks by Rob Brown

Other Decks in Programming

Transcript

  1. Blocks Blocks are a proposed addition to C. Like a

    function pointer, except it also stores the context the block was created in. Similar to closures, lambdas, and anonymous functions in other languages.
  2. Blocks Declaration Syntax: returnType (^blockName) (Arguments) Blocks may be anonymous.

    Definition Syntax: ^ returnType (Arguments) { code; } The return type and arguments are optional. GCD provides function pointer variants to the block APIs.
  3. Blocks Blocks can modify local variables outside of their scope

    if the variables have the new __block keyword. Global and static variables can be modified without the __block keyword. Blocks automatically retain Objective-C objects. C objects must be manually retained.
  4. GCD

  5. What is GCD? GCD is a lightweight multithreading engine. Uses

    a thread pool. Developers create queues of blocks rather than threads. Uses lock-less exclusion rather than mutual exclusion. Replaces blocking and polling APIs.
  6. Why Multithread on a Single Core? Keeps the UI responsive.

    UI code runs on the main thread. Everything else runs on a background thread. Prevents the main thread from blocking or waiting.
  7. Global Queues Four global queues: Main, Low, Default, and High.

    Only the main thread services the main queue. The three other queues determine the priority of background tasks. Enqueuing is thread safe.
  8. User Queues Developers can create their own queues. Create a

    queue for each task, subsystem, or resource. Queues should use reverse-DNS naming. Example: edu.byu.cocoaheads.networkqueue Jedi Level
  9. User Queues All queues must eventually drain to a global

    queue. Queues can be organized into arbitrary hierarchies. Don’t create loops! Jedi Level
  10. User Queues Queue 2 Queue 1 Queue 3 Default Priority

    Queue 1 Queue 2 Queue 3 Default Jedi Level ≠
  11. Dispatch Sources Queues can respond to low-level events. Decouples monitoring

    and event handling. Avoids polling for an event. Example: Polling for a directory change or socket available. Dispatch sources can be suspended, resumed, and cancelled. Jedi Level
  12. Semaphores Semaphores are used to create locks. Available if you

    need them. Usually block the running thread. The availability of the semaphore can be checked without blocking (i.e. Test and Set). Sith Level