SlideShare a Scribd company logo
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
• …

More Related Content

What's hot

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
vorfeed chen
 
无锁编程
无锁编程无锁编程
无锁编程
vorfeed chen
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
stefanmayer13
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
Alex Miller
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
Robert Brown
 
Jafka guide
Jafka guideJafka guide
Jafka guide
Ady Liu
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
명신 김
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan Huang
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
Srinivasan Raghavan
 
Ice mini guide
Ice mini guideIce mini guide
Ice mini guide
Ady Liu
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
Sebastian Springer
 
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 typescript
Katy 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 Dispatch
Matteo Battaglio
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
Gyuwon Yi
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
Rafael Winterhalter
 

What's hot (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
 

Viewers also liked

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
iMasters
 
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
 
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
CatherineGordon2022
 
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
Rogé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
 
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
Samsung Open Source Group
 
Objective C Tricks
Objective C TricksObjective C Tricks
Objective C Tricks
Inova 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 Questions
Clark 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 industry
Arindam 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
 

Viewers also liked (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#
 

Similar to Grand Central Dispatch

Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
PGConf 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-2
Rajeev Rastogi (KRR)
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
MongoDB
 
Multithreading on iOS
Multithreading on iOSMultithreading on iOS
Multithreading on iOS
Make School
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
Rajeev Rastogi (KRR)
 
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
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
Dushyant Nasit
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj 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 Programming
Mandeep 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.docx
bradburgess22840
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
SudhanshiBakre1
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
Gephi Consortium
 
Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
Luke Donnet
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
GlobalLogic Ukraine
 
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
Spark Summit
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume LaforgeGroovy Ecosystem - JFokus 2011 - Guillaume Laforge
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Guillaume Laforge
 

Similar to 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
 

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 

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

Editor's Notes

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