Pune-Cocoa: Blocks and GCD

34
Blocks & GCD

description

Blocks is a cool concept and is very much needed for performance improvements and responsiveness. GCD helps run blocks effortlessly by scheduling on a desired queue, priority and lots more.

Transcript of Pune-Cocoa: Blocks and GCD

Page 1: Pune-Cocoa: Blocks and GCD

Blocks & GCD

Page 2: Pune-Cocoa: Blocks and GCD

• History• GCD• Queues• Blocks• Syntax and Examples• Demo

Page 3: Pune-Cocoa: Blocks and GCD

Grand Central Dispatch

Page 4: Pune-Cocoa: Blocks and GCD

History• Historically, microprocessors gained speed

by running at faster and faster clock speeds; and software become automatically faster.

• Processor clock speeds began to reach a limit because power consumption and heat became problematic, particularly for mobile systems.

• CPU vendors shifted their focus from increasing clock speed to putting multiple processor cores into a single CPU

• software no longer automatically becomes faster.

Page 5: Pune-Cocoa: Blocks and GCD

History• We required threads to make use of

multithreading, NSThread is not that simple to use for each and every small data processing task, need locks.

• NSOprationQueue was an alternative, but not so lightweight and required some boilerplate code

• Or use o performSelectorInBackground:withObject:o performSelectorOnMainThread:withObject:w

aitUntilDone:

Page 6: Pune-Cocoa: Blocks and GCD

Solution

• The dominant model for concurrent programming—threads and locks—is too difficult to be worth the effort for most applications. To write a an efficient application for multi- core using threads, you need to: – Break each logical task down to a single thread

Lock data that is in danger of being changed by two threads at onceBuild a thread manager to run only as many threads as there are available cores Hope that no other applications running on the system are using the processor cores

Page 7: Pune-Cocoa: Blocks and GCD

How?

• GCD shifts the responsibility for managing threads and their execution from applications to the operating system.

• Units of work are described as blocks in your code, while queues are used to organize blocks based on how you believe they need to be executed.

• GCD has a multicore execution engine that reads the queues created by each application and assigns work from the queues to the threads it is managing.

Page 8: Pune-Cocoa: Blocks and GCD

Hooray!• Apple introduced Grand Central

Dispatch and Blocks for SnowLeopard; and decided to remove support for PPC.

• Apple came up with multicore HandHelds, soon after blocks and GCD were announced for iOS

Page 9: Pune-Cocoa: Blocks and GCD

Programming Model• Blocks are used as a Unit of Work• Dispatch Objects - reference counted, uses

dispatch_retain() and dispatch_release()• Queues (four system defined) are used to

execute Blocks– Serial / Concurrent

• Event Sources – associate blocks/queues to asynchronous event source e.g. timer, socket

• A thread-pool of max 512 threads can be maintained, old threads are reused

Page 10: Pune-Cocoa: Blocks and GCD

Queues

Page 11: Pune-Cocoa: Blocks and GCD

Queues

• Most of the intelligence behind Grand Central Dispatch is provided by queues. – Global Queues– Private Queues– Main Queue

• A queue can execute operation in Sync or Async

Page 12: Pune-Cocoa: Blocks and GCD

Queuesdispatch_queue_t dispatch_get_global_queue( long priority, unsigned long flags);DISPATCH_QUEUE_PRIORITY_HIGHDISPATCH_QUEUE_PRIORITY_DEFAULTDISPATCH_QUEUE_PRIORITY_LOW

dispatch_queue_t dispatch_queue_create( const char *label dispatch_queue_attr_t attr);

dispatch_queue_t dispatch_get_main_queue(void);

Page 13: Pune-Cocoa: Blocks and GCD

Using Queues

Page 14: Pune-Cocoa: Blocks and GCD

Using Queues

Page 15: Pune-Cocoa: Blocks and GCD

Using Queues• the block that's submitted with the barrier function doesn't run

concurrently with other work on that queue• pointless on a serial queue• non-functional when used on the global queues

Page 16: Pune-Cocoa: Blocks and GCD

Blocks

Page 17: Pune-Cocoa: Blocks and GCD

Blocks: What is it?• Blocks are a nonstandard extension

added by Apple Inc. to the C, C++, and Objective-C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+.– wikipedia

Page 18: Pune-Cocoa: Blocks and GCD

What is it?• A block is an anonymous inline collection of

code that:– Has a typed argument list just like a function

Page 19: Pune-Cocoa: Blocks and GCD

What is it?• A block is an anonymous inline collection of

code that:– Has an inferred or declared return type

Page 20: Pune-Cocoa: Blocks and GCD

What is it?• A block is an anonymous inline collection of

code that:– Can capture state from the lexical scope within

which it is defined

Page 21: Pune-Cocoa: Blocks and GCD

What is it?• A block is an anonymous inline collection of

code that:– Can optionally modify the state of the lexical scope

Page 22: Pune-Cocoa: Blocks and GCD

What is it?• A block is an anonymous inline collection of

code that:– Can share the potential for modification with other

blocks defined within the same lexical scope• Multiple blocks in the same lexical score

shares the same instance.• If a variable is __block is is passed as

reference and hence can be accessed by multiple blocks

Page 23: Pune-Cocoa: Blocks and GCD

What is it?• A block is an anonymous inline collection of

code that:– Can continue to share and modify state defined

within the lexical scope (the stack frame) after the lexical scope (the stack frame) has been destroyed• Each __block has a __strong reference hence even if

current stack frame is destroyed it can work on that variable.• The compiler and runtime arrange that all variables

referenced from the block are preserved for the life of all copies of the block

Page 24: Pune-Cocoa: Blocks and GCD

What is it?• You can copy a block and even pass it to other

threads for deferred execution (or, within its own thread, to a runloop). (use Block_copy instead)

Page 25: Pune-Cocoa: Blocks and GCD

Blocks Usage

• Used for lightweight task, Blocks represent typically small, self-contained pieces of code.

• They’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.

Page 26: Pune-Cocoa: Blocks and GCD

Small, Self contained

Page 27: Pune-Cocoa: Blocks and GCD

Work over over items in a collection

Page 28: Pune-Cocoa: Blocks and GCD

Callbacks

• Asynchronus Network tasks• Snippet from MKNetworkEngine.m by @mugunthkumar

Page 29: Pune-Cocoa: Blocks and GCD

Usage in cocoa

• Asynchronus UI tasks

Page 30: Pune-Cocoa: Blocks and GCD

Under the Hood• Extracted from " Pro Multithreading and Memory Management for iOS and OS X with ARC,

Grand Central Dispatch, and Blocks" by Kazuki Sakamoto and Tomohiko Furumoto

void (^blk)(void) = ^{printf("Block\n");};

is translated to static void __main_block_func_0(struct __main_block_impl_0 *__cself) {printf("Block\n"); }

by compiler, there is lot of other boilerplate code created to help invocation of this method and other blocks operation (sharing a variable, copy, pass by reference)

Page 31: Pune-Cocoa: Blocks and GCD

Dispatch Source

Page 32: Pune-Cocoa: Blocks and GCD

Dispatch Source

• dispatch source is an object which monitors for one of following event :– Mach port send right state changes.– Mach port receive right state changes.– External process state change.– File descriptor ready for read.– File descriptor ready for write.– Filesystem node event. (kqueue)– POSIX signal.– Custom timer.– Custom event.

Page 33: Pune-Cocoa: Blocks and GCD

Dispatch Source example

Page 34: Pune-Cocoa: Blocks and GCD

Thank You!

• Sources:– Apple Documentation– libdispatch Wiki– CGD Technology Brief

Prepared for PuneCocoaBy Prashant Rane

(@the69geeks)