SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Downloaden Sie, um offline zu lesen
^{ }
        blocks
                   and


                 Raphael Sebbe
                  creaceed.com
cocoaheads.be        @rsebbe
Ways to Get More
• We can’t get more GHz out of silicon
• Parallelism is the solution
 •   Nowadays, multi-core systems is the rule

     •   On it’s way to mobile devices (iPad2)

 •   Specialized hardware, like GPU, too

     •   Already there on mobile
GPU




            Core
                          SIMD

            Multi-



Cloud
Farms/
                 Core Image



                         OpenCL



                                  GLSL
                                         Data-driven




                  Accelerate




             Threads


             Grand
            Central
            Dispatch


  Load
              Cron
Balancing
                                         Task-driven




            OpenMP
Overview
• Blocks & GCD are 2 different beasts
 • New language feature
 • Efficiently define tasks, and execute them

• They complement each other nicely
Blocks
• Concept of closure from functional
  programming
                                   Lisp, Caml, Haskell,
• Blocks                           Javascript, etc.

 • are an extension of C language
 • store a piece of executable code
 • capture the execution context
 • are objects (Obj-C or C-based API)
Definition of a Block
// Simple one
void (^myblock)() = ^{
! printf(“Hellon”);
};
myblock();


// With one arg
void (^myblock)(int) = ^(int arg){
! printf(“Hello arg=%dn”, arg);
};
myblock(1);


// With a return value
int (^myblock)(int) = ^(int arg){
! printf(“Hello arg=%dn”, arg);
! return arg + 1;                    ~ anonymous
};                                   function pointer
int r = myblock(1);
Typedef’ing a Block
// Typedef of a block type
typedef void (^MyBlockType)(NSURL *assetURL, NSError
*error);

MyBlockType myBlock = ^(NSURL *assetURL, NSError
*error) {
! // Some code
};


// Syntax of untyped block as Obj-C method argument
- (void)addPlayersToMatch:(GKMatch *)match
matchRequest:(GKMatchRequest *)matchRequest
completionHandler:(void (^)(NSError *))handler
Execution Context (1/3)
• Definition of a block captures the
  execution context
• Variable of standard C types are copied
    int a = 3;

    // Context is captured at it’s current state
    void (^myblock)() = ^{
    ! printf(“Hello a=%dn”, a);
    };

    a = 5;

    myblock(); // outputs “Hello a=3”
Execution Context (2/3)
• Captured objects are retained
    id dict = [[NSDictionary alloc] init];

    // Referenced objects are retained
    void (^myblock)() = ^{
    ! NSLog(“Hello dict=%@n”, dict);
    };

    [dict release];

    myblock(); // outputs “Hello dict=....”       Remark: For
                                               referenced ivar, it’s
                                              self that gets
                                               retained. Possible
                                                  retain cycles.
Execution Context (3/3)
• Shared (R/W) variables with __block
      __block int a = 3;

      // Context is captured at it’s current state
      void (^myblock)() = ^{
      ! a += 1;
      ! printf(“Hello a=%dn”, a);
      };

      a = 5;
                                                 Remark:
      myblock(); // outputs “Hello a=6”       __block objects
                                              (id, etc.) are not
                                                 retained
Block Storage
      • When defined, blocks are stack objects,
          only valid in the definition scope
      • Must be copied to heap if used outside of
          creation context
if (x) {                              if (x) {
!   block = ^{ printf("truen");};    !   block = ^{ printf("truen");};
} else {                              !   block = [block copy];
!   block = ^{ printf("falsen");};   } else {
}                                     !   block = ^{ printf("falsen");};
block(); // unsafe!!!                 !   block = [block copy];Remark:
                                      }
                                      block(); // safe!!!
                                                            If your method
                                      [block release];    takes a block as
                                                          arg., always copy
                                                              it.
Blocks Advantages
• Idea: invoke this “block of code” later.
• Callback API are naturally expressed
 • Good replacement to your many didEnd:
    methods
• Task queueing / parallelism much easier
 • See GCD
Grand Central Dispatch

• Need for parallelism that scales
• Easy to program for wide adoption
• Parallelism examples
 • iTunes - Coverflow, downloads...
 • iPhoto - import, uploads, preview
 • Twitter Profile Pictures, etc.
Grand Central Dispatch
• Multi-core needs threads

• Say you have a 4-core machine, you need 4
  threads for maximum throughput.
• Well... No.

• This is a pre-emptive world
Threads (1/2)
• Optimal number of threads for your app
 • Number of (virtual) cores
 • Load from other apps
 • Thread state (low speed I/O)
• This continuously changes
• Consequences: unused or overused cores
Threads (2/2)
• 3 problems with threads:
 • Too low-level, you shouldn’t waste your time
    at this (when to create/destroy them)
 • You generally don’t have easy access to
    global system info
 • Thread programming is hard (sync
    primitives, etc.)
GCD Concept
• Tasks in Queues         Out
  In



  In                      Out




  Core                    Q’s are
                     lightweight, have
  Core               as many as you
                          want
Why Q’s
•   Goal: Best use of cores

    •   Let the system create/destroy threads for you

    •   Write less code: wide adoption

    •   Better overall user experience (responsiveness)

•   Technical: Less contention

    •   Fewer locks

    •   Scales much better with

        •   number of tasks

        •   number of cores
Queue Types
• Serial queues: one task at a time Serial Q’s are
 • User queues                      themselves sync
                                      primitives
 • Main queue
• Concurrent queues: multiple tasks
 • 3 priority levels                    Only the
                                    global one on
                                         10.6 / iOS4
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);
Adding Tasks
// Synchronous, blocks until code is executed
dispatch_sync(queue, ^{
! // task code
});

dispatch_apply(count, queue, ^(size_t i){
! // process ith
});



// Asynchronous, returns immediately to caller
dispatch_async(queue, ^{
! // task code                                     API exists for
});
                                                 function pointers
dispatch_after(when, queue, ^{                      too.
! // task code
});
NSOperationQueue



Core

Core
Adding Operations
// Synchronous, blocks until code is executed
NSOperationQueue *queue = [[NSOQ alloc] init];
!
NSBlockOperation *op1 = [NSBlockOperation
! blockOperationWithBlock:^{
! ! // some code! !
! }];
NSBlockOperation *op2 = [NSBlockOperation
! blockOperationWithBlock:^{                    Predates
! ! // some code!
! }];                                         GCD, has some
!                                            odd APIs. Now built
[op2 addDependency:op1];
!
                                               on top of it.
[queue addOperation:op1];
[queue addOperation:op2];
[queue addOperationWithBlock:^{
! // some code! !
                                               You can set
}];                                         the max concurrent
                                               ops.
APIs using Blocks (1/2)
 // Collections (NSDictionary / NSArray / NSSet)
 - (void)enumerateKeysAndObjectsWithOptions:
 (NSEnumerationOptions)opts usingBlock:(void (^)(id
 key, id obj, BOOL *stop))block

 - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id
 key, id obj, BOOL *stop))predicate
                                          Patterns for collections:
 - (NSArray *)keysSortedByValueUsingComparator:
 (NSComparator)cmptr
                                         enumeration, mutation,
                                          tests, comparison
 // NSRegularExpression
 - (void)enumerateMatchesInString:(NSString *)string
 options:(NSMatchingOptions)options range:(NSRange)
 range usingBlock:(void (^)(NSTextCheckingResult
 *result, NSMatchingFlags flags, BOOL *stop))block
APIs using Blocks (2/2)
 // ALAssetsLibrary
 - (void)enumerateGroupsWithTypes:(ALAssetsGroupType)
 types usingBlock:(ALAssetsLib...ationResultsBlock)
 enumerationBlock failureBlock:
 (ALAssetsLib...ssFailureBlock)failureBlock


 // Game Kit                             Patterns for accessors:
 - (void)loadScoresWithCompletionHandler:(void (^)
                                         callback / handler
 (NSArray *scores, NSError *error))completionHandler


 // AVFoundation, AppKit, many other, etc.
Xcode Demo’s
• Extending UIAlertView using blocks

• Delving inside Elasty video stabilization
  method
Threads
• Threads are not dead yet, they are just
  under your feet. (see crashlogs)
• Some uses are well suited at threads
 • Real time needs
 • OpenGL
 • Core Image
 • ...
What’s Next?
• Check WWDC videos [210, 308, 322]
• Dispatch group (dispatch_group_*)
• Source (dispatch_source_*)
• Semaphores (dispatch_semaphore_*)
• ARC interactions
• File / Memory I/O
• Target queues
Thank you!
 (Q&A?)

Weitere ähnliche Inhalte

Was ist angesagt?

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference CountingRobert Brown
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBXESUG
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORPESUG
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Stefan Marr
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortStefan Marr
 
iOS Development with Blocks
iOS Development with BlocksiOS Development with Blocks
iOS Development with BlocksJeff Kelley
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt CommunicationAndreas Jakl
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Dinh Pham
 

Was ist angesagt? (20)

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Squeak DBX
Squeak DBXSqueak DBX
Squeak DBX
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORP
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
 
Streams in Node.js
Streams in Node.jsStreams in Node.js
Streams in Node.js
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low Effort
 
iOS Development with Blocks
iOS Development with BlocksiOS Development with Blocks
iOS Development with Blocks
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
NodeJS
NodeJSNodeJS
NodeJS
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?Asynchronous I/O in NodeJS - new standard or challenges?
Asynchronous I/O in NodeJS - new standard or challenges?
 

Andere mochten auch

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
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
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
 
Evolve 2014 iBeacons and Contextual Location Awareness in iOS and Android apps
Evolve 2014 iBeacons and Contextual Location Awareness in iOS and Android appsEvolve 2014 iBeacons and Contextual Location Awareness in iOS and Android apps
Evolve 2014 iBeacons and Contextual Location Awareness in iOS and Android appsJames Montemagno
 
Linares: Experto en coaching. Marzo 2015
Linares: Experto en coaching. Marzo 2015Linares: Experto en coaching. Marzo 2015
Linares: Experto en coaching. Marzo 2015nodo23
 
Movimiento Libertario Ecuador - Reporte 2006
Movimiento Libertario Ecuador - Reporte 2006 Movimiento Libertario Ecuador - Reporte 2006
Movimiento Libertario Ecuador - Reporte 2006 Juan Fernando Carpio
 
Proyecto licenciados reunidos
Proyecto licenciados reunidosProyecto licenciados reunidos
Proyecto licenciados reunidossportscomunity
 
Myanmar Business Today - Vol 2, Issue 31
Myanmar Business Today - Vol 2, Issue 31Myanmar Business Today - Vol 2, Issue 31
Myanmar Business Today - Vol 2, Issue 31Myanmar Business Today
 
Tralee Active Town May 2015
Tralee Active Town  May 2015Tralee Active Town  May 2015
Tralee Active Town May 2015Xhemile Nabolli
 
1317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten1
1317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten11317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten1
1317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten1Cecilia Noboa
 
Update from ILRI People and Organizational Development Directorate
Update from ILRI People and Organizational Development DirectorateUpdate from ILRI People and Organizational Development Directorate
Update from ILRI People and Organizational Development DirectorateILRI
 
Sostenibilidad del SNS y modelo de prestacion de servicios: Andalucia
Sostenibilidad del SNS y modelo de prestacion de servicios:  AndaluciaSostenibilidad del SNS y modelo de prestacion de servicios:  Andalucia
Sostenibilidad del SNS y modelo de prestacion de servicios: AndaluciaJose Luis Rocha Castilla
 

Andere mochten auch (20)

Android Application Development at JFokus 2011
Android Application Development at JFokus 2011Android Application Development at JFokus 2011
Android Application Development at JFokus 2011
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Objective C Tricks
Objective C TricksObjective C Tricks
Objective C Tricks
 
iOS Application Lifecycle
iOS Application LifecycleiOS Application Lifecycle
iOS Application Lifecycle
 
Evolve 2014 iBeacons and Contextual Location Awareness in iOS and Android apps
Evolve 2014 iBeacons and Contextual Location Awareness in iOS and Android appsEvolve 2014 iBeacons and Contextual Location Awareness in iOS and Android apps
Evolve 2014 iBeacons and Contextual Location Awareness in iOS and Android apps
 
Linares: Experto en coaching. Marzo 2015
Linares: Experto en coaching. Marzo 2015Linares: Experto en coaching. Marzo 2015
Linares: Experto en coaching. Marzo 2015
 
Charcoal
CharcoalCharcoal
Charcoal
 
387 c
387 c387 c
387 c
 
120389232 reiki-kundalini
120389232 reiki-kundalini120389232 reiki-kundalini
120389232 reiki-kundalini
 
Movimiento Libertario Ecuador - Reporte 2006
Movimiento Libertario Ecuador - Reporte 2006 Movimiento Libertario Ecuador - Reporte 2006
Movimiento Libertario Ecuador - Reporte 2006
 
Proyecto licenciados reunidos
Proyecto licenciados reunidosProyecto licenciados reunidos
Proyecto licenciados reunidos
 
Myanmar Business Today - Vol 2, Issue 31
Myanmar Business Today - Vol 2, Issue 31Myanmar Business Today - Vol 2, Issue 31
Myanmar Business Today - Vol 2, Issue 31
 
Curso excel septiembre 21
Curso excel septiembre 21Curso excel septiembre 21
Curso excel septiembre 21
 
Tralee Active Town May 2015
Tralee Active Town  May 2015Tralee Active Town  May 2015
Tralee Active Town May 2015
 
Durkheim
DurkheimDurkheim
Durkheim
 
Procedimientos- QSO
Procedimientos- QSOProcedimientos- QSO
Procedimientos- QSO
 
1317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten1
1317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten11317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten1
1317747663 n 031-norma-y-protocolo-para-la-prevencion-deteccion-y-aten1
 
Update from ILRI People and Organizational Development Directorate
Update from ILRI People and Organizational Development DirectorateUpdate from ILRI People and Organizational Development Directorate
Update from ILRI People and Organizational Development Directorate
 
Sostenibilidad del SNS y modelo de prestacion de servicios: Andalucia
Sostenibilidad del SNS y modelo de prestacion de servicios:  AndaluciaSostenibilidad del SNS y modelo de prestacion de servicios:  Andalucia
Sostenibilidad del SNS y modelo de prestacion de servicios: Andalucia
 
CamCube 4.0 Produktfamilie
CamCube 4.0 ProduktfamilieCamCube 4.0 Produktfamilie
CamCube 4.0 Produktfamilie
 

Ähnlich wie Blocks & GCD

Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)Jigar Maheshwari
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormDavorin Vukelic
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java DevelopersMuhammad Abdullah
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Felix Geisendörfer
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical StuffPetr Dvorak
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWeare-Legion
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraAllen Wirfs-Brock
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?Kyle Oba
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer mcwilson1
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Kenneth Geisshirt
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelVitaly Nikolenko
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 

Ähnlich wie Blocks & GCD (20)

Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)Blocks and GCD(Grand Central Dispatch)
Blocks and GCD(Grand Central Dispatch)
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Objective-c for Java Developers
Objective-c for Java DevelopersObjective-c for Java Developers
Objective-c for Java Developers
 
Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?Nodejs - Should Ruby Developers Care?
Nodejs - Should Ruby Developers Care?
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
iOS 2 - The practical Stuff
iOS 2 - The practical StuffiOS 2 - The practical Stuff
iOS 2 - The practical Stuff
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
无锁编程
无锁编程无锁编程
无锁编程
 
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
«ReactiveCocoa и MVVM» — Николай Касьянов, SoftWear
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
What Makes Objective C Dynamic?
What Makes Objective C Dynamic?What Makes Objective C Dynamic?
What Makes Objective C Dynamic?
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
Exploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernelExploitation of counter overflows in the Linux kernel
Exploitation of counter overflows in the Linux kernel
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 

Mehr von rsebbe

Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Codersebbe
 
Advanced Imaging on iOS
Advanced Imaging on iOSAdvanced Imaging on iOS
Advanced Imaging on iOSrsebbe
 
iOS 7 URL Session & Motion FX APIs
iOS 7 URL Session & Motion FX APIsiOS 7 URL Session & Motion FX APIs
iOS 7 URL Session & Motion FX APIsrsebbe
 
CeedMath & CeedGL, Let's talk 3D...
CeedMath & CeedGL, Let's talk 3D...CeedMath & CeedGL, Let's talk 3D...
CeedMath & CeedGL, Let's talk 3D...rsebbe
 
Designing an Objective-C Framework about 3D
Designing an Objective-C Framework about 3DDesigning an Objective-C Framework about 3D
Designing an Objective-C Framework about 3Drsebbe
 
Computer-aided Diagnosis of Pulmonary Embolism in Opacified CT Images
Computer-aided Diagnosis of Pulmonary Embolism in Opacified CT ImagesComputer-aided Diagnosis of Pulmonary Embolism in Opacified CT Images
Computer-aided Diagnosis of Pulmonary Embolism in Opacified CT Imagesrsebbe
 
Xcode, Basics and Beyond
Xcode, Basics and BeyondXcode, Basics and Beyond
Xcode, Basics and Beyondrsebbe
 

Mehr von rsebbe (7)

Orthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable CodeOrthogonality: A Strategy for Reusable Code
Orthogonality: A Strategy for Reusable Code
 
Advanced Imaging on iOS
Advanced Imaging on iOSAdvanced Imaging on iOS
Advanced Imaging on iOS
 
iOS 7 URL Session & Motion FX APIs
iOS 7 URL Session & Motion FX APIsiOS 7 URL Session & Motion FX APIs
iOS 7 URL Session & Motion FX APIs
 
CeedMath & CeedGL, Let's talk 3D...
CeedMath & CeedGL, Let's talk 3D...CeedMath & CeedGL, Let's talk 3D...
CeedMath & CeedGL, Let's talk 3D...
 
Designing an Objective-C Framework about 3D
Designing an Objective-C Framework about 3DDesigning an Objective-C Framework about 3D
Designing an Objective-C Framework about 3D
 
Computer-aided Diagnosis of Pulmonary Embolism in Opacified CT Images
Computer-aided Diagnosis of Pulmonary Embolism in Opacified CT ImagesComputer-aided Diagnosis of Pulmonary Embolism in Opacified CT Images
Computer-aided Diagnosis of Pulmonary Embolism in Opacified CT Images
 
Xcode, Basics and Beyond
Xcode, Basics and BeyondXcode, Basics and Beyond
Xcode, Basics and Beyond
 

Kürzlich hochgeladen

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
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
 
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
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
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
 
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 is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 

Kürzlich hochgeladen (20)

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
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
 
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
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
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
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
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
 
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 is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 

Blocks & GCD

  • 1. ^{ } blocks and Raphael Sebbe creaceed.com cocoaheads.be @rsebbe
  • 2. Ways to Get More • We can’t get more GHz out of silicon • Parallelism is the solution • Nowadays, multi-core systems is the rule • On it’s way to mobile devices (iPad2) • Specialized hardware, like GPU, too • Already there on mobile
  • 3. GPU Core SIMD Multi- Cloud Farms/ Core Image OpenCL GLSL Data-driven Accelerate Threads Grand Central Dispatch Load Cron Balancing Task-driven OpenMP
  • 4. Overview • Blocks & GCD are 2 different beasts • New language feature • Efficiently define tasks, and execute them • They complement each other nicely
  • 5. Blocks • Concept of closure from functional programming Lisp, Caml, Haskell, • Blocks Javascript, etc. • are an extension of C language • store a piece of executable code • capture the execution context • are objects (Obj-C or C-based API)
  • 6. Definition of a Block // Simple one void (^myblock)() = ^{ ! printf(“Hellon”); }; myblock(); // With one arg void (^myblock)(int) = ^(int arg){ ! printf(“Hello arg=%dn”, arg); }; myblock(1); // With a return value int (^myblock)(int) = ^(int arg){ ! printf(“Hello arg=%dn”, arg); ! return arg + 1; ~ anonymous }; function pointer int r = myblock(1);
  • 7. Typedef’ing a Block // Typedef of a block type typedef void (^MyBlockType)(NSURL *assetURL, NSError *error); MyBlockType myBlock = ^(NSURL *assetURL, NSError *error) { ! // Some code }; // Syntax of untyped block as Obj-C method argument - (void)addPlayersToMatch:(GKMatch *)match matchRequest:(GKMatchRequest *)matchRequest completionHandler:(void (^)(NSError *))handler
  • 8. Execution Context (1/3) • Definition of a block captures the execution context • Variable of standard C types are copied int a = 3; // Context is captured at it’s current state void (^myblock)() = ^{ ! printf(“Hello a=%dn”, a); }; a = 5; myblock(); // outputs “Hello a=3”
  • 9. Execution Context (2/3) • Captured objects are retained id dict = [[NSDictionary alloc] init]; // Referenced objects are retained void (^myblock)() = ^{ ! NSLog(“Hello dict=%@n”, dict); }; [dict release]; myblock(); // outputs “Hello dict=....” Remark: For referenced ivar, it’s self that gets retained. Possible retain cycles.
  • 10. Execution Context (3/3) • Shared (R/W) variables with __block __block int a = 3; // Context is captured at it’s current state void (^myblock)() = ^{ ! a += 1; ! printf(“Hello a=%dn”, a); }; a = 5; Remark: myblock(); // outputs “Hello a=6” __block objects (id, etc.) are not retained
  • 11. Block Storage • When defined, blocks are stack objects, only valid in the definition scope • Must be copied to heap if used outside of creation context if (x) { if (x) { ! block = ^{ printf("truen");}; ! block = ^{ printf("truen");}; } else { ! block = [block copy]; ! block = ^{ printf("falsen");}; } else { } ! block = ^{ printf("falsen");}; block(); // unsafe!!! ! block = [block copy];Remark: } block(); // safe!!! If your method [block release]; takes a block as arg., always copy it.
  • 12. Blocks Advantages • Idea: invoke this “block of code” later. • Callback API are naturally expressed • Good replacement to your many didEnd: methods • Task queueing / parallelism much easier • See GCD
  • 13. Grand Central Dispatch • Need for parallelism that scales • Easy to program for wide adoption • Parallelism examples • iTunes - Coverflow, downloads... • iPhoto - import, uploads, preview • Twitter Profile Pictures, etc.
  • 14. Grand Central Dispatch • Multi-core needs threads • Say you have a 4-core machine, you need 4 threads for maximum throughput. • Well... No. • This is a pre-emptive world
  • 15. Threads (1/2) • Optimal number of threads for your app • Number of (virtual) cores • Load from other apps • Thread state (low speed I/O) • This continuously changes • Consequences: unused or overused cores
  • 16. Threads (2/2) • 3 problems with threads: • Too low-level, you shouldn’t waste your time at this (when to create/destroy them) • You generally don’t have easy access to global system info • Thread programming is hard (sync primitives, etc.)
  • 17.
  • 18.
  • 19. GCD Concept • Tasks in Queues Out In In Out Core Q’s are lightweight, have Core as many as you want
  • 20. Why Q’s • Goal: Best use of cores • Let the system create/destroy threads for you • Write less code: wide adoption • Better overall user experience (responsiveness) • Technical: Less contention • Fewer locks • Scales much better with • number of tasks • number of cores
  • 21. Queue Types • Serial queues: one task at a time Serial Q’s are • User queues themselves sync primitives • Main queue • Concurrent queues: multiple tasks • 3 priority levels Only the global one on 10.6 / iOS4
  • 22. 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);
  • 23. Adding Tasks // Synchronous, blocks until code is executed dispatch_sync(queue, ^{ ! // task code }); dispatch_apply(count, queue, ^(size_t i){ ! // process ith }); // Asynchronous, returns immediately to caller dispatch_async(queue, ^{ ! // task code API exists for }); function pointers dispatch_after(when, queue, ^{ too. ! // task code });
  • 25. Adding Operations // Synchronous, blocks until code is executed NSOperationQueue *queue = [[NSOQ alloc] init]; ! NSBlockOperation *op1 = [NSBlockOperation ! blockOperationWithBlock:^{ ! ! // some code! ! ! }]; NSBlockOperation *op2 = [NSBlockOperation ! blockOperationWithBlock:^{ Predates ! ! // some code! ! }]; GCD, has some ! odd APIs. Now built [op2 addDependency:op1]; ! on top of it. [queue addOperation:op1]; [queue addOperation:op2]; [queue addOperationWithBlock:^{ ! // some code! ! You can set }]; the max concurrent ops.
  • 26. APIs using Blocks (1/2) // Collections (NSDictionary / NSArray / NSSet) - (void)enumerateKeysAndObjectsWithOptions: (NSEnumerationOptions)opts usingBlock:(void (^)(id key, id obj, BOOL *stop))block - (NSSet *)keysOfEntriesPassingTest:(BOOL (^)(id key, id obj, BOOL *stop))predicate Patterns for collections: - (NSArray *)keysSortedByValueUsingComparator: (NSComparator)cmptr enumeration, mutation, tests, comparison // NSRegularExpression - (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange) range usingBlock:(void (^)(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop))block
  • 27. APIs using Blocks (2/2) // ALAssetsLibrary - (void)enumerateGroupsWithTypes:(ALAssetsGroupType) types usingBlock:(ALAssetsLib...ationResultsBlock) enumerationBlock failureBlock: (ALAssetsLib...ssFailureBlock)failureBlock // Game Kit Patterns for accessors: - (void)loadScoresWithCompletionHandler:(void (^) callback / handler (NSArray *scores, NSError *error))completionHandler // AVFoundation, AppKit, many other, etc.
  • 28. Xcode Demo’s • Extending UIAlertView using blocks • Delving inside Elasty video stabilization method
  • 29.
  • 30. Threads • Threads are not dead yet, they are just under your feet. (see crashlogs) • Some uses are well suited at threads • Real time needs • OpenGL • Core Image • ...
  • 31. What’s Next? • Check WWDC videos [210, 308, 322] • Dispatch group (dispatch_group_*) • Source (dispatch_source_*) • Semaphores (dispatch_semaphore_*) • ARC interactions • File / Memory I/O • Target queues