SlideShare une entreprise Scribd logo
1  sur  21
Grand Central Dispatch

      Nguyen Dinh Quan
          12/2012
Contents
1.   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)
GCD: An Overview
Concurrency
    do multiple things simultaneously

    take advantage of multiple cores

Traditional way: create multiple threads
    not efficiently: unused or overused cores

    low-level, waste time to create and destroy thread

    thread programming is hard

Modern way: Grand Central Dispatch (GCD)
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
GCD: An Overview
                           in waiting




                            a queue - FIFO
put task into queue                                      dequeued tasks
to execute                                               are being executed




   if there are some queues, they could still execute tasks concurrently
Blocks
blocks
   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
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/Blo
cks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
Dispatch Queues
Overview
 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
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
Dispatch Queues
Adding tasks to a queue
synchronous

   // 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
   });
Dispatch Queues
more

suspend 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.
Operation Queues
Overview
cocoa operations
       an object-oriented way for GCD
       objective-C based, so easy to use in iOS

step
       creating operations

       executing operations
Operation Queues
Creating operations
by selector
NSInvocationOperation* theOp = [[NSInvocationOperation alloc]
initWithTarget:self selector:@selector(myTaskMethod:) object:data];

by block
NSBlockOperation *operation = [NSBlockOperation
blockOperationWithBlock:^{
     NSLog(@"Doing something...");
}];

//you can add more blocks
[operation addExecutionBlock:^{
     NSLog(@"Another block");
}];

[operation setCompletionBlock:^{
     NSLog(@"Doing something once the operation has finished");
}];
Operation Queues
Executing operations
adding operation to NSOperationQueue

NSOperationQueue* 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/Operation
Objects.html#//apple_ref/doc/uid/TP40008091-CH101-SW1
Operation Queues
More
suspending and resuming operation queues
 - (void)setSuspended:(BOOL)suspend

cancels all queued and executing operation
 - (void)cancelAllOperation


reference links:
https://developer.apple.com/library/mac/#documentation/Cocoa/Refe
rence/NSOperationQueue_class/Reference/Reference.html
https://developer.apple.com/library/mac/#documentation/Cocoa/Refe
rence/NSOperation_class/Reference/Reference.html
Dispatch Group
use to group some blocks and track when they all complete

it can be helpful when progress can’t be made until all of the specified
tasks 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");
 });
Dispatch Semaphore
In computer science, a semaphore is a variable or abstract data type that provides
a simple but useful abstraction for controlling access by multiple processes to a
common resource in a parallel programming or multi user environment.
                                                                       (wikipedia)
use a dispatch semaphore to regulate the number of tasks simultaneously
accessing some resources

// Create the semaphore, specifying the initial pool size
dispatch_semaphore_t fd_sema = dispatch_semaphore_create
(getdtablesize() / 2);

// Wait for a free file descriptor
dispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER);
fd = open("/etc/services", O_RDONLY);

// Release the file descriptor when done
close(fd);
dispatch_semaphore_signal(fd_sema);
Examples
Example 1: Download Image with dispatch queue

dispatch_queue_t queue = dispatch_queue_create(”image_queue”
      , NULL);
//dispatch_async to get the image data
dispatch_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
Examples
Example 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 a
background thread, and call one of the callback blocks when it completes or fails!
Examples
External 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
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
• …

Contenu connexe

Tendances

Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
Allan Huang
 

Tendances (20)

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
无锁编程
无锁编程无锁编程
无锁编程
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
Jafka guide
Jafka guideJafka guide
Jafka guide
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 

En vedette

Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015
Ben Asher
 
Android Application Development at JFokus 2011
Android Application Development at JFokus 2011Android Application Development at JFokus 2011
Android Application Development at JFokus 2011
Anders Göransson
 
iOS Application Lifecycle
iOS Application LifecycleiOS Application Lifecycle
iOS Application Lifecycle
Siva Prasad K V
 

En vedette (13)

Programação Assíncrona com C# 5
Programação Assíncrona com C# 5Programação Assíncrona com C# 5
Programação Assíncrona com C# 5
 
Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015Grand Central Dispatch - iOS Conf SG 2015
Grand Central Dispatch - iOS Conf SG 2015
 
Opportunities in Resource Management Industries in Tees Valley
Opportunities in Resource Management Industries in Tees ValleyOpportunities in Resource Management Industries in Tees Valley
Opportunities in Resource Management Industries in Tees Valley
 
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
 
IAsyncResult Pattern ou Asynchronous Programming Model (APM)
IAsyncResult Pattern ou Asynchronous Programming Model (APM)IAsyncResult Pattern ou Asynchronous Programming Model (APM)
IAsyncResult Pattern ou Asynchronous Programming Model (APM)
 
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
 
Android Application Development at JFokus 2011
Android Application Development at JFokus 2011Android Application Development at JFokus 2011
Android Application Development at JFokus 2011
 
Clang: More than just a C/C++ Compiler
Clang: More than just a C/C++ CompilerClang: More than just a C/C++ Compiler
Clang: More than just a C/C++ Compiler
 
Objective C Tricks
Objective C TricksObjective C Tricks
Objective C Tricks
 
iOS Application Lifecycle
iOS Application LifecycleiOS Application Lifecycle
iOS Application Lifecycle
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview Questions
 
Top technology trends in supply chain & logistics industry
Top technology trends in supply chain & logistics industryTop technology trends in supply chain & logistics industry
Top technology trends in supply chain & logistics industry
 
Programação assíncrona com C#
Programação assíncrona com C#Programação assíncrona com C#
Programação assíncrona com C#
 

Similaire à Grand Central Dispatch

Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
bradburgess22840
 

Similaire à Grand Central Dispatch (20)

Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
 
Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docxIn Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
In Class AssignmetzCST280W13a-1.pdfCST 280 In-Class Pract.docx
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-MallaKerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
Kerberizing Spark: Spark Summit East talk by Abel Rincon and Jorge Lopez-Malla
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Grand Central Dispatch

  • 1. Grand Central Dispatch Nguyen Dinh Quan 12/2012
  • 2. Contents 1. 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. GCD: An Overview Concurrency do multiple things simultaneously take advantage of multiple cores Traditional way: create multiple threads not efficiently: unused or overused cores low-level, waste time to create and destroy thread thread programming is hard Modern way: Grand Central Dispatch (GCD)
  • 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. GCD: An Overview in waiting a queue - FIFO put task into queue dequeued tasks to execute are being executed if there are some queues, they could still execute tasks concurrently
  • 6. Blocks blocks 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. 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/Blo cks/Articles/bxGettingStarted.html#//apple_ref/doc/uid/TP40007502-CH7-SW1
  • 8. Dispatch Queues Overview 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. 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. Dispatch Queues Adding tasks to a queue synchronous // 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. Dispatch Queues more suspend 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. Operation Queues Overview cocoa operations an object-oriented way for GCD objective-C based, so easy to use in iOS step creating operations executing operations
  • 13. Operation Queues Creating operations by selector NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data]; by block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"Doing something..."); }]; //you can add more blocks [operation addExecutionBlock:^{ NSLog(@"Another block"); }]; [operation setCompletionBlock:^{ NSLog(@"Doing something once the operation has finished"); }];
  • 14. Operation Queues Executing operations adding operation to NSOperationQueue NSOperationQueue* 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/Operation Objects.html#//apple_ref/doc/uid/TP40008091-CH101-SW1
  • 15. Operation Queues More suspending and resuming operation queues - (void)setSuspended:(BOOL)suspend cancels all queued and executing operation - (void)cancelAllOperation reference links: https://developer.apple.com/library/mac/#documentation/Cocoa/Refe rence/NSOperationQueue_class/Reference/Reference.html https://developer.apple.com/library/mac/#documentation/Cocoa/Refe rence/NSOperation_class/Reference/Reference.html
  • 16. Dispatch Group use to group some blocks and track when they all complete it can be helpful when progress can’t be made until all of the specified tasks 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. Dispatch Semaphore In computer science, a semaphore is a variable or abstract data type that provides a simple but useful abstraction for controlling access by multiple processes to a common resource in a parallel programming or multi user environment. (wikipedia) use a dispatch semaphore to regulate the number of tasks simultaneously accessing some resources // Create the semaphore, specifying the initial pool size dispatch_semaphore_t fd_sema = dispatch_semaphore_create (getdtablesize() / 2); // Wait for a free file descriptor dispatch_semaphore_wait(fd_sema, DISPATCH_TIME_FOREVER); fd = open("/etc/services", O_RDONLY); // Release the file descriptor when done close(fd); dispatch_semaphore_signal(fd_sema);
  • 18. Examples Example 1: Download Image with dispatch queue dispatch_queue_t queue = dispatch_queue_create(”image_queue” , NULL); //dispatch_async to get the image data dispatch_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. Examples Example 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 a background thread, and call one of the callback blocks when it completes or fails!
  • 20. Examples External 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. 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 • …

Notes de l'éditeur

  1. Our topic today is Grand Central Dispatch.It takes about 15 minutes to covers all issues
  2. Here are contents of my presentation
  3. 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.
  4. 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.
  5. 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.
  6. 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 ^{ .. }