3. 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.
4. 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.
5. 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.
7. 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.
8. 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.
10. 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.
12. User Queues Jedi
Level
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
13. User Queues Jedi
Level
All queues must eventually drain to a global queue.
Queues can be organized into arbitrary hierarchies.
Don’t create loops!
15. Dispatch Sources Jedi
Level
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.
16. Semaphores Sith
Level
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).