SlideShare a Scribd company logo
Blocks & GCD
•   History
•   GCD
•   Queues
•   Blocks
•   Syntax and Examples
•   Demo
Grand Central
  Dispatch
History
• Historically, microprocessors gained speed
  by running at faster and faster clock
  speeds; and software become
  automatically faster.
• Processor clock speeds began to reach a
  limit because power consumption and heat
  became problematic, particularly for mobile
  systems.
• CPU vendors shifted their focus from
  increasing clock speed to putting multiple
  processor cores into a single CPU
• software no longer automatically becomes
History
• We required threads to make use of
  multithreading, NSThread is not that simple
  to use for each and every small data
  processing task, need locks.
• NSOprationQueue was an alternative, but
  not so lightweight and required some
  boilerplate code
• Or use
  o performSelectorInBackground:withObject:
  o performSelectorOnMainThread:withObject:wait
    UntilDone:
Solution
• The dominant model for concurrent
  programming—threads and locks—is too difficult
  to be worth the effort for most applications. To
  write a an efficient application for multi- core
  using threads, you need to:
  – Break each logical task down to a single thread
    Lock data that is in danger of being changed by two
    threads at once
    Build a thread manager to run only as many threads as
    there are available cores Hope that no other
    applications running on the system are using the
    processor cores
How?
• GCD shifts the responsibility for managing
  threads and their execution from applications to
  the operating system.
• Units of work are described as blocks in your
  code, while queues are used to organize blocks
  based on how you believe they need to be
  executed.
• GCD has a multicore execution engine that reads
  the queues created by each application and
  assigns work from the queues to the threads it is
  managing.
Hooray!
• Apple introduced Grand Central Dispatch
  and Blocks for SnowLeopard; and decided
  to remove support for PPC.
• Apple came up with multicore HandHelds,
  soon after blocks and GCD were
  announced for iOS
Programming Model
• Blocks are used as a Unit of Work
• Dispatch Objects - reference counted, uses
  dispatch_retain() and dispatch_release()
• Queues (four system defined) are used to
  execute Blocks
  – Serial / Concurrent
• Event Sources – associate blocks/queues to
  asynchronous event source e.g. timer, socket
• A thread-pool of max 512 threads can be
  maintained, old threads are reused
Queues
Queues
• Most of the intelligence behind Grand Central
  Dispatch is provided by queues.
  – Global Queues
  – Private Queues
  – Main Queue


• A queue can execute operation in Sync or
  Async
Queues
dispatch_queue_t dispatch_get_global_queue(
  long priority,
  unsigned long flags);
DISPATCH_QUEUE_PRIORITY_HIGH
DISPATCH_QUEUE_PRIORITY_DEFAULT
DISPATCH_QUEUE_PRIORITY_LOW

dispatch_queue_t dispatch_queue_create(
  const char *label
  dispatch_queue_attr_t attr);

dispatch_queue_t dispatch_get_main_queue(void);
Using Queues
Using Queues
Using Queues
• the block that's submitted with the barrier function doesn't
  run concurrently with other work on that queue
• pointless on a serial queue
• non-functional when used on the global queues
Blocks
Blocks: What is it?
• Blocks are a nonstandard extension added
  by Apple Inc. to the C, C++, and Objective-
  C programming languages that uses a
  lambda expression-like syntax to create
  closures within these languages. Blocks
  are supported for programs developed for
  Mac OS X 10.6+ and iOS 4.0+.
  – wikipedia
What is it?
• A block is an anonymous inline collection of
  code that:
  – Has a typed argument list just like a function
What is it?
• A block is an anonymous inline collection of
  code that:
  – Has an inferred or declared return type
What is it?
• A block is an anonymous inline collection of
  code that:
  – Can capture state from the lexical scope within
    which it is defined
What is it?
• A block is an anonymous inline collection of
  code that:
  – Can optionally modify the state of the lexical scope
What is it?
• A block is an anonymous inline collection of
  code that:
  – Can share the potential for modification with other
    blocks defined within the same lexical scope
     • Multiple blocks in the same lexical score shares the
       same instance.
     • If a variable is __block is is passed as reference
       and hence can be accessed by multiple blocks
What is it?
• A block is an anonymous inline collection of
  code that:
  – Can continue to share and modify state defined
    within the lexical scope (the stack frame) after the
    lexical scope (the stack frame) has been destroyed
     • Each __block has a __strong reference hence even if
       current stack frame is destroyed it can work on that
       variable.
     • The compiler and runtime arrange that all variables
       referenced from the block are preserved for the life of
       all copies of the block
What is it?
• You can copy a block and even pass it to other
  threads for deferred execution (or, within its
  own thread, to a runloop). (use Block_copy
  instead)
Blocks Usage
• Used for lightweight task, Blocks represent
  typically small, self-contained pieces of code.
• They’re particularly useful as a means of
  encapsulating units of work that may be
  executed concurrently, or over items in a
  collection, or as a callback when another
  operation has finished.
Small, Self contained
Work over over items in a collection
Callbacks
• Asynchronus Network tasks
     • Snippet from MKNetworkEngine.m by @mugunthkumar
Usage in cocoa
• Asynchronus UI tasks
Under the Hood
•   Extracted from "Pro Multithreading and Memory Management for iOS and OS X with ARC,
    Grand Central Dispatch, and Blocks" by Kazuki Sakamoto and Tomohiko Furumoto


void (^blk)(void) = ^{printf("Blockn");};
is translated to
static void __main_block_func_0(struct __main_block_impl_0
*__cself) {printf("Blockn"); }
by compiler, there is lot of other boilerplate
code created to help invocation of this method
and other blocks operation (sharing a variable,
copy, pass by reference)
Dispatch Source
Dispatch Source
• dispatch source is an object which monitors for
  one of following event :
  –   Mach port send right state changes.
  –   Mach port receive right state changes.
  –   External process state change.
  –   File descriptor ready for read.
  –   File descriptor ready for write.
  –   Filesystem node event. (kqueue)
  –   POSIX signal.
  –   Custom timer.
  –   Custom event.
Dispatch Source example
Thank You!
• Sources:
  – Apple Documentation
  – libdispatch Wiki
  – CGD Technology Brief




                           Prepared for PuneCocoa
                                    By Prashant Rane
                                      (@the69geeks)

More Related Content

PPTX
Grand Central Dispatch
PDF
GCD and OperationQueue.
PDF
Blocks & GCD
KEY
Grand Central Dispatch Design Patterns
PDF
Objective-C Blocks and Grand Central Dispatch
PPT
iOS Multithreading
PPTX
Effective java - concurrency
PDF
Facebook C++网络库Wangle调研
Grand Central Dispatch
GCD and OperationQueue.
Blocks & GCD
Grand Central Dispatch Design Patterns
Objective-C Blocks and Grand Central Dispatch
iOS Multithreading
Effective java - concurrency
Facebook C++网络库Wangle调研

What's hot (20)

PDF
无锁编程
PDF
Java Concurrency Gotchas
PPTX
Functional Reactive Programming with RxJS
PDF
Loom and concurrency latest
KEY
Threading in iOS / Cocoa Touch
PDF
Java Concurrency in Practice
PPTX
Concurrency in Java
ODP
Java Concurrency
PPT
Java New Evolution
PPTX
Introduction to TPL
PDF
Java Concurrency Idioms
PPTX
Basics of Java Concurrency
PPTX
The Java memory model made easy
PDF
Clojure made-simple - John Stevenson
ODP
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
PDF
JUnit5 and TestContainers
PPTX
Java concurrency - Thread pools
KEY
Automatic Reference Counting
PDF
camel-scala.pdf
无锁编程
Java Concurrency Gotchas
Functional Reactive Programming with RxJS
Loom and concurrency latest
Threading in iOS / Cocoa Touch
Java Concurrency in Practice
Concurrency in Java
Java Concurrency
Java New Evolution
Introduction to TPL
Java Concurrency Idioms
Basics of Java Concurrency
The Java memory model made easy
Clojure made-simple - John Stevenson
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
JUnit5 and TestContainers
Java concurrency - Thread pools
Automatic Reference Counting
camel-scala.pdf
Ad

Similar to Pune-Cocoa: Blocks and GCD (20)

PDF
PPTX
PDF
Latest (storage IO) patterns for cloud-native applications
PDF
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
PPTX
UNIT -5 EMBEDDED DRIVERS AND APPLICATION PORTING.pptx
PPT
Processes and Threads in Windows Vista
KEY
The Why and How of Scala at Twitter
PDF
Ippevent : openshift Introduction
PDF
Apache Spark Tutorial
PDF
threads (1).pdfmjlkjfwjgliwiufuaiusyroayr
PDF
Flexible Indexing in Lucene 4.0
PPT
Distributed & Highly Available server applications in Java and Scala
PDF
Machine Learning With H2O vs SparkML
PPTX
.net Based Component Technologies
PPTX
Sanger, upcoming Openstack for Bio-informaticians
PPTX
Flexible compute
PPTX
Kafka overview v0.1
PDF
A Closer Look at Apache Kudu
PPTX
Real Time Operating System
PPTX
Realtime traffic analyser
Latest (storage IO) patterns for cloud-native applications
COMMitMDE'18: Eclipse Hawk: model repository querying as a service
UNIT -5 EMBEDDED DRIVERS AND APPLICATION PORTING.pptx
Processes and Threads in Windows Vista
The Why and How of Scala at Twitter
Ippevent : openshift Introduction
Apache Spark Tutorial
threads (1).pdfmjlkjfwjgliwiufuaiusyroayr
Flexible Indexing in Lucene 4.0
Distributed & Highly Available server applications in Java and Scala
Machine Learning With H2O vs SparkML
.net Based Component Technologies
Sanger, upcoming Openstack for Bio-informaticians
Flexible compute
Kafka overview v0.1
A Closer Look at Apache Kudu
Real Time Operating System
Realtime traffic analyser
Ad

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
A Presentation on Artificial Intelligence
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Machine learning based COVID-19 study performance prediction
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Getting Started with Data Integration: FME Form 101
PDF
Encapsulation theory and applications.pdf
PPTX
Spectroscopy.pptx food analysis technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Machine Learning_overview_presentation.pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPT
Teaching material agriculture food technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Accuracy of neural networks in brain wave diagnosis of schizophrenia
A Presentation on Artificial Intelligence
A comparative analysis of optical character recognition models for extracting...
NewMind AI Weekly Chronicles - August'25-Week II
Machine learning based COVID-19 study performance prediction
OMC Textile Division Presentation 2021.pptx
SOPHOS-XG Firewall Administrator PPT.pptx
Getting Started with Data Integration: FME Form 101
Encapsulation theory and applications.pdf
Spectroscopy.pptx food analysis technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Assigned Numbers - 2025 - Bluetooth® Document
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Encapsulation_ Review paper, used for researhc scholars
Machine Learning_overview_presentation.pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Univ-Connecticut-ChatGPT-Presentaion.pdf
Teaching material agriculture food technology

Pune-Cocoa: Blocks and GCD

  • 2. History • GCD • Queues • Blocks • Syntax and Examples • Demo
  • 3. Grand Central Dispatch
  • 4. History • Historically, microprocessors gained speed by running at faster and faster clock speeds; and software become automatically faster. • Processor clock speeds began to reach a limit because power consumption and heat became problematic, particularly for mobile systems. • CPU vendors shifted their focus from increasing clock speed to putting multiple processor cores into a single CPU • software no longer automatically becomes
  • 5. History • We required threads to make use of multithreading, NSThread is not that simple to use for each and every small data processing task, need locks. • NSOprationQueue was an alternative, but not so lightweight and required some boilerplate code • Or use o performSelectorInBackground:withObject: o performSelectorOnMainThread:withObject:wait UntilDone:
  • 6. Solution • The dominant model for concurrent programming—threads and locks—is too difficult to be worth the effort for most applications. To write a an efficient application for multi- core using threads, you need to: – Break each logical task down to a single thread Lock data that is in danger of being changed by two threads at once Build a thread manager to run only as many threads as there are available cores Hope that no other applications running on the system are using the processor cores
  • 7. How? • GCD shifts the responsibility for managing threads and their execution from applications to the operating system. • Units of work are described as blocks in your code, while queues are used to organize blocks based on how you believe they need to be executed. • GCD has a multicore execution engine that reads the queues created by each application and assigns work from the queues to the threads it is managing.
  • 8. Hooray! • Apple introduced Grand Central Dispatch and Blocks for SnowLeopard; and decided to remove support for PPC. • Apple came up with multicore HandHelds, soon after blocks and GCD were announced for iOS
  • 9. Programming Model • Blocks are used as a Unit of Work • Dispatch Objects - reference counted, uses dispatch_retain() and dispatch_release() • Queues (four system defined) are used to execute Blocks – Serial / Concurrent • Event Sources – associate blocks/queues to asynchronous event source e.g. timer, socket • A thread-pool of max 512 threads can be maintained, old threads are reused
  • 11. Queues • Most of the intelligence behind Grand Central Dispatch is provided by queues. – Global Queues – Private Queues – Main Queue • A queue can execute operation in Sync or Async
  • 12. Queues dispatch_queue_t dispatch_get_global_queue( long priority, unsigned long flags); DISPATCH_QUEUE_PRIORITY_HIGH DISPATCH_QUEUE_PRIORITY_DEFAULT DISPATCH_QUEUE_PRIORITY_LOW dispatch_queue_t dispatch_queue_create( const char *label dispatch_queue_attr_t attr); dispatch_queue_t dispatch_get_main_queue(void);
  • 15. Using Queues • the block that's submitted with the barrier function doesn't run concurrently with other work on that queue • pointless on a serial queue • non-functional when used on the global queues
  • 17. Blocks: What is it? • Blocks are a nonstandard extension added by Apple Inc. to the C, C++, and Objective- C programming languages that uses a lambda expression-like syntax to create closures within these languages. Blocks are supported for programs developed for Mac OS X 10.6+ and iOS 4.0+. – wikipedia
  • 18. What is it? • A block is an anonymous inline collection of code that: – Has a typed argument list just like a function
  • 19. What is it? • A block is an anonymous inline collection of code that: – Has an inferred or declared return type
  • 20. What is it? • A block is an anonymous inline collection of code that: – Can capture state from the lexical scope within which it is defined
  • 21. What is it? • A block is an anonymous inline collection of code that: – Can optionally modify the state of the lexical scope
  • 22. What is it? • A block is an anonymous inline collection of code that: – Can share the potential for modification with other blocks defined within the same lexical scope • Multiple blocks in the same lexical score shares the same instance. • If a variable is __block is is passed as reference and hence can be accessed by multiple blocks
  • 23. What is it? • A block is an anonymous inline collection of code that: – Can continue to share and modify state defined within the lexical scope (the stack frame) after the lexical scope (the stack frame) has been destroyed • Each __block has a __strong reference hence even if current stack frame is destroyed it can work on that variable. • The compiler and runtime arrange that all variables referenced from the block are preserved for the life of all copies of the block
  • 24. What is it? • You can copy a block and even pass it to other threads for deferred execution (or, within its own thread, to a runloop). (use Block_copy instead)
  • 25. Blocks Usage • Used for lightweight task, Blocks represent typically small, self-contained pieces of code. • They’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.
  • 27. Work over over items in a collection
  • 28. Callbacks • Asynchronus Network tasks • Snippet from MKNetworkEngine.m by @mugunthkumar
  • 29. Usage in cocoa • Asynchronus UI tasks
  • 30. Under the Hood • Extracted from "Pro Multithreading and Memory Management for iOS and OS X with ARC, Grand Central Dispatch, and Blocks" by Kazuki Sakamoto and Tomohiko Furumoto void (^blk)(void) = ^{printf("Blockn");}; is translated to static void __main_block_func_0(struct __main_block_impl_0 *__cself) {printf("Blockn"); } by compiler, there is lot of other boilerplate code created to help invocation of this method and other blocks operation (sharing a variable, copy, pass by reference)
  • 32. Dispatch Source • dispatch source is an object which monitors for one of following event : – Mach port send right state changes. – Mach port receive right state changes. – External process state change. – File descriptor ready for read. – File descriptor ready for write. – Filesystem node event. (kqueue) – POSIX signal. – Custom timer. – Custom event.
  • 34. Thank You! • Sources: – Apple Documentation – libdispatch Wiki – CGD Technology Brief Prepared for PuneCocoa By Prashant Rane (@the69geeks)