Grand Central Dispatch

5,713 views

Published on

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,713
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
172
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • Our topic today is Grand Central Dispatch.It takes about 15 minutes to covers all issues
  • Here are contents of my presentation
  • Firstly, I want to talk about an overview of GCDGCD is a new technology to perform concurrent programming.As you know, creating multiple threads is traditional way to do this.Assume, if you want to download a file in background, you will have to create a thread and attach this work on this thread.But threading is not efficient because it doesn’t take advantage of multiple core efficiently.
  • So that apple has invented GCD to do concurrency easier, more modern and efficient.It moves thread management down to system level.All you have to do is only creating tasks and putting them into dispatch queues.
  • You can see it more “ro rang” in this picture.Two steps to perform concurrently a task. Defines a task and put it into the dispatch queues.
  • Let’s go to step 1.You define a task by using block.Blocks are an extension of C language.To define a block you simply “wraps” code in ^{ .. }
  • Grand Central Dispatch

    1. 1. Grand Central Dispatch Nguyen Dinh Quan 12/2012
    2. 2. Contents1. Grand Central Dispatch (GCD): An Overview (3 slides)2. Blocks (2 slides)3. Dispatch Queues (4 slides)4. Operation Queues (4 slides)5. Dispatch Group (1 slide)6. Dispatch Semaphore (1 slide)7. Examples (3 slides)8. References (1 slide)
    3. 3. GCD: An OverviewConcurrency do multiple things simultaneously take advantage of multiple coresTraditional way: create multiple threads not efficiently: unused or overused cores low-level, waste time to create and destroy thread thread programming is hardModern way: Grand Central Dispatch (GCD)
    4. 4. GCD: An Overview easier, more modern and efficient than threads high-level, move thread management down to system level define tasks and add them to an appropriate dispatch queues task management and execution is more efficient than threads new concepts: task and dispatch queues
    5. 5. GCD: An Overview in waiting a queue - FIFOput task into queue dequeued tasksto execute are being executed if there are some queues, they could still execute tasks concurrently
    6. 6. Blocksblocks task is defined by using block blocks are an extension of C language encapsulate code like a function by using ^{ … }define blocks // Simple one void (^myblock)() = ^{ printf(“Hellon”); }; myblock(); //executing block
    7. 7. Blocks (cont.) with arguments void (^myblock)(int) = ^(int arg){ printf(“Helloarg=%dn”,arg); }; myblock(1);with return value int (^myblock)(int) = ^(int arg){ printf(“Hello arg=%dn”,arg); return arg+1; }; int r = myblock(1);http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
    8. 8. Dispatch QueuesOverview dispatch queues C based, procedural programming easy way to perform tasks asynchronously and concurrently add a task into the queues to perform it 3-types of dispatch queues serial (private dispatch queue) execute one task at a time concurrent (global dispatch queue) execute one or more task concurrently main dispatch queues execute task on main thread
    9. 9. Dispatch Queues Creating dispatch queues dispatch_queue_t queue; // Main (serial) queue queue = dispatch_get_main_queue(); // User (serial) queue queue = dispatch_queue_create(“com.mycompany.qname”, NULL); // Global (concurrent) queue, with priority queue = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);notes: there are 3 global queues by priority: HIGH, DEFAULT, LOW you can create as many serial queue as you need
    10. 10. Dispatch QueuesAdding tasks to a queuesynchronous // Synchronous, blocks until code is executed dispatch_sync(queue, ^{ //taskcode });asynchronous // Asynchronous, returns immediately to caller dispatch_async(queue, ^{ //taskcode }); dispatch_after(when, queue, ^{ //taskcode });
    11. 11. Dispatch Queuesmoresuspend a queue dispatch_suspend(queue);resume a queue dispatch_resume(queue);memory management Dispatch queues are reference-counted data types.When you create a serial dispatch queue, it has an initial reference count of 1.You can use the dispatch_retain and dispatch_release functions to increment and decrement that reference count as needed. When the reference count of a queue reaches zero, the system asynchronously deallocates the queue.
    12. 12. Operation QueuesOverviewcocoa operations an object-oriented way for GCD objective-C based, so easy to use in iOSstep creating operations executing operations
    13. 13. Operation QueuesCreating operationsby selectorNSInvocationOperation* theOp = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(myTaskMethod:) object:data];by blockNSBlockOperation *operation = [NSBlockOperationblockOperationWithBlock:^{ NSLog(@"Doing something...");}];//you can add more blocks[operation addExecutionBlock:^{ NSLog(@"Another block");}];[operation setCompletionBlock:^{ NSLog(@"Doing something once the operation has finished");}];
    14. 14. Operation QueuesExecuting operationsadding operation to NSOperationQueueNSOperationQueue* aQueue = [[NSOperationQueue alloc] init];[aQueue addOperation:anOp]; // Add a single operation// Add multiple operations[aQueue addOperations:anArrayOfOps waitUntilFinished:NO];[aQueue addOperationWithBlock:^{ /* Do something. */}];You can execute operations manually by reading document from:http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW1
    15. 15. Operation QueuesMoresuspending and resuming operation queues - (void)setSuspended:(BOOL)suspendcancels all queued and executing operation - (void)cancelAllOperationreference links:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.htmlhttps://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html
    16. 16. Dispatch Groupuse to group some blocks and track when they all completeit can be helpful when progress can’t be made until all of the specifiedtasks are complete dispatch_queue_t queue = dispatch_get_global_queue(0,0); dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group,queue,^{ NSLog(@"Block 1"); }); dispatch_group_async(group,queue,^{ NSLog(@"Block 2"); }); dispatch_group_notify(group,queue,^{ NSLog(@"Final block is executed last after 1 and 2"); });
    17. 17. Dispatch SemaphoreIn computer science, a semaphore is a variable or abstract data type that providesa simple but useful abstraction for controlling access by multiple processes to acommon resource in a parallel programming or multi user environment. (wikipedia)use a dispatch semaphore to regulate the number of tasks simultaneouslyaccessing some resources// Create the semaphore, specifying the initial pool sizedispatch_semaphore_t fd_sema = dispatch_semaphore_create(getdtablesize() / 2);// Wait for a free file descriptordispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER);fd = open("/etc/services", O_RDONLY);// Release the file descriptor when doneclose(fd);dispatch_semaphore_signal(fd_sema);
    18. 18. ExamplesExample 1: Download Image with dispatch queuedispatch_queue_t queue = dispatch_queue_create(”image_queue” , NULL);//dispatch_async to get the image datadispatch_async(queue, ^{ NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url]]; UIImage *anImage = [UIImage imageWithData:data]; [self.images setValue:anImage forKey:userID]; UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; //dispatch_async on the main queue to update the UI dispatch_async(dispatch_get_main_queue(), ^{ cell.imageView.image = anImage; });});run a heavy work on background and update GUI on main thread
    19. 19. ExamplesExample 2: Callback block #import "ASIHTTPRequest.h” - (void)getImage { __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:sourceURL]; [request setCompletionBlock:^{ NSLog(@"Image downloaded."); NSData *data = [request responseData]; image = [[UIImage alloc] initWithData:data]; }]; [request setFailedBlock:^{ NSLog(@"Error downloading image"); }]; [request startAsynchronous]; }the OS will automatically run the code to download the image on abackground thread, and call one of the callback blocks when it completes or fails!
    20. 20. ExamplesExternal example• http://www.raywenderlich.com/4295/multithreading-and- grand-central-dispatch-on-ios-for-beginners-tutorial• http://www.raywenderlich.com/19788/how-to-use- nsoperations-and-nsoperationqueues• https://github.com/SlaunchaMan/GCDExample
    21. 21. References• http://en.wikipedia.org/wiki/Grand_Central_Dispatch• http://developer.apple.com/library/mac/#documentation/Perf ormance/Reference/GCD_libdispatch_Ref/Reference/referenc e.html• http://developer.apple.com/library/mac/#documentation/Ge neral/Conceptual/ConcurrencyProgrammingGuide/Introductio n/Introduction.html#//apple_ref/doc/uid/TP40008091• http://cocoasamurai.blogspot.com/2009/09/guide-to-blocks- grand-central-dispatch.html• …

    ×