SlideShare ist ein Scribd-Unternehmen logo
1 von 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
• …

Weitere ähnliche Inhalte

Was ist angesagt?

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研vorfeed chen
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJSstefanmayer13
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingRobert Brown
 
Jafka guide
Jafka guideJafka guide
Jafka guideAdy Liu
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guideAdy Liu
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
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 typescriptKaty Slemon
 
How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)How to Test Asynchronous Code (v2)
How to Test Asynchronous Code (v2)Felix Geisendörfer
 
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 DispatchMatteo Battaglio
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPLGyuwon Yi
 

Was ist angesagt? (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
 

Andere mochten auch

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# 5iMasters
 
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 2015Ben Asher
 
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 ValleyCatherineGordon2022
 
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.5Rogério Moraes de Carvalho
 
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)Rogério Moraes de Carvalho
 
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...Rogério Moraes de Carvalho
 
Android Application Development at JFokus 2011
Android Application Development at JFokus 2011Android Application Development at JFokus 2011
Android Application Development at JFokus 2011Anders Göransson
 
Objective C Tricks
Objective C TricksObjective C Tricks
Objective C TricksInova LLC
 
iOS Application Lifecycle
iOS Application LifecycleiOS Application Lifecycle
iOS Application LifecycleSiva Prasad K V
 
iOS Developer Interview Questions
iOS Developer Interview QuestionsiOS Developer Interview Questions
iOS Developer Interview QuestionsClark Davidson
 
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 industryArindam Bakshi
 
Programação assíncrona com C#
Programação assíncrona com C#Programação assíncrona com C#
Programação assíncrona com C#Giovanni Bassi
 

Andere mochten auch (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#
 

Ähnlich wie Grand Central Dispatch

Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native CompilationPGConf APAC
 
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-2Rajeev Rastogi (KRR)
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOSMake School
 
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...TAISEEREISA
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded ProgrammingSri Prasanna
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
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...David Walker
 
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 ProgrammingMandeep Singh
 
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.docxbradburgess22840
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
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-MallaSpark Summit
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGuillaume Laforge
 

Ähnlich wie 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
 

Kürzlich hochgeladen

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 

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 • …

Hinweis der Redaktion

  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 ^{ .. }