SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Nikmesoft Ltd
Multiple Background
Threads
Linh NGUYEN
Lecture 4
Nikmesoft Ltd
Contents
2
Overview1
NSThread & NSRunLoop2
Blocks & NotificationCenter3
GCD & NSOperations4
Exercise 45
Nikmesoft Ltd
Multiple Background Threads
Overview
3
Nikmesoft Ltd
Overview
 When an application is launched, the system creates a
thread of execution for the application, called "main."
 The main thread is also sometimes called the UI
thread.
 The system does not create a separate thread for each
instance of a component. All components that run in
the same process are instantiated in the UI thread,
and system calls to each component are dispatched
from that thread.
4
Nikmesoft Ltd
Overview
 If everything is happening in the UI thread,
performing long operations such as network access or
database queries will block the whole UI.
 When the thread is blocked, no events can be
dispatched, including drawing events.
5
Nikmesoft Ltd
Overview
 Even worse, if the UI thread is blocked for more than a
few seconds (about 5 seconds currently) the user is
presented with the infamous "application not
responding" (ANR) dialog (Android)
6
Nikmesoft Ltd
Overview
 The user might then decide to quit your application
and uninstall it if they are unhappy.
7
Nikmesoft Ltd
Overview
 There are simply two rules to single thread model:
 Do not block the UI thread
 Do not access the UI toolkit from outside the UI thread
8
Nikmesoft Ltd
Overview
 Having multiple threads in an application provides two
very important potential advantages:
 Multiple threads can improve an application’s perceived
responsiveness.
 Multiple threads can improve an application’s real-time
performance on multicore systems.
9
Nikmesoft Ltd
Multiple Background Threads
NSThread & NSRunloop
10
Nikmesoft Ltd
NSThread & NSRunloop
 Create new Thread
 [NSThread detachNewThreadSelector:@selector(startTheBackgro
undJob) toTarget:self withObject:nil];
 Create subclass of NSThread and override main method
 Run on UI Thread
 [self performSelectorOnMainThread:@selector(updateUI) withObj
ect:nil waitUntilDone:NO];
11
Nikmesoft Ltd
NSThread & NSRunloop
 The problem
 Touches aren’t the only source of input to an
iPhone application. Ex socket listening
 But you don’t want the UI to lock up whilst it’s
listening – you still want input from the user to be
dealt with promptly.
 Similarly, you might want events to be triggered
automatically at certain time intervals, but without
locking up the application in the interim.
12
Nikmesoft Ltd
NSThread & NSRunloop
 The Solution
 Using a separate thread
 NSRunLoop
13
Nikmesoft Ltd
NSThread & NSRunloop
 NSRunLoop
 A run loop is an abstraction that (among other things) provides a
mechanism to handle system input sources (sockets, ports, files,
keyboard, mouse, timers, etc).
 Each NSThread has its own run loop, which can be accessedvia
the currentRunLoop method.
 A run loop for a given thread will wait until one or more of its input
sources has some data or event, then fire the appropriate input
handler(s) to process each input source that is "ready.".
14
Nikmesoft Ltd
NSThread & NSRunloop
 NSRunLoop
 After doing so, it will then return to its loop, processing input from
various sources, and "sleeping" if there is no work to do.
15
Nikmesoft Ltd
NSThread & NSRunloop
16
Design Tips
 Avoid Creating Threads Explicitly
 Keep Your Threads Reasonably Busy
 Avoid Shared Data Structures
 Terminate Your Threads Cleanly
Nikmesoft Ltd
Example 4.1
17
photos.plist
Nikmesoft Ltd
Multiple Background Threads
Blocks
18
Nikmesoft Ltd
Blocks
 Blocks
 Blocks are Objective-C’s anonymous functions.
 Function and function pointer
 Creating Blocks
 Blocks use all the same mechanics as normal functions. You can
declare a block variable just like you would declare a function,
define the block as though you would implement a function, and
then call the block as if it were a function:
19
Nikmesoft Ltd
Blocks
 Creating Blocks
20
Nikmesoft Ltd
Blocks
 Blocks as Method Parameters
 Storing blocks in variables is occasionally useful, but in the real
world, they’re more likely to be used as method parameters. They
solve the same problem as function pointers, but the fact that they
can be defined inline makes the resulting code much easier to
read.
21
Nikmesoft Ltd
Blocks
 Blocks as Method Parameters
22
Nikmesoft Ltd
Blocks
 Defining Block Types
 Storing blocks in variables is occasionally useful, but in the real
world, they’re more likely to be used as method parameters. They
solve the same problem as function pointers, but the fact that they
can be defined inline makes the resulting code much easier to
read.
23
Nikmesoft Ltd
Blocks
 Defining Block Types
24
Nikmesoft Ltd
Multiple Background Threads
NotificationCenter
25
Nikmesoft Ltd
NotificationCenter
 NSNotificationCenter
 NSNotificationCenter is one way you can communicate with other
objects in your project.
 Post and receive a notification
26
Nikmesoft Ltd
NotificationCenter
 Post and receive a notification
27
Nikmesoft Ltd
NotificationCenter
 Post and receive a notification
28
Nikmesoft Ltd
NotificationCenter
 Why we need to use NSNotificationCenter
 Delegation
 Notification Center
 Key value observing(KVO)
29
Nikmesoft Ltd
NotificationCenter
 Delegation
 Pros
• Ability to have multiple protocols defined one controller, each with different
delegates.
• No third party object required to maintain / monitor the communication
process.
• Ability to receive a returned value from a called protocol method. This means
that a delegate can help provide information back to a controller
30
Nikmesoft Ltd
NotificationCenter
 Delegation
 Pros
• Very strict syntax. All events to be heard are clearly defined in the delegate
protocol.
• Compile time Warnings / Errors if a method is not implemented as it should be
by a delegate.
• Protocol defined within the scope of the controller only.
• Very traceable, and easy to identify flow of control within an application.
31
Nikmesoft Ltd
NotificationCenter
 Delegation
 Cons
• Many lines of code required to define: 1. the protocol definition, 2. the delegate
property in the controller, and 3. the implementation of the delegate method
definitions within the delegate itself.
• Although possible, it can be difficult and the pattern does not really lend itself
to have multiple delegates of the same protocol in a controller (telling multiple
objects about the same event)
32
Nikmesoft Ltd
NotificationCenter
 NotificationCenter
 Pros
• Easy to implement, with not many lines of code.
• Can easily have multiple objects reacting to the same notification being
posted.
• Controller can pass in a context (dictionary) object with custom information
(userInfo) related to the notification being posted.
33
Nikmesoft Ltd
NotificationCenter
 NotificationCenter
 Cons
• No compile time to checks to ensure that notifications are correctly handled by
observers.
• Required to un-register with the notification center if your previously registered
object is deallocated.
• Not very traceable. Attempting to debug issues related to application flow and
control can be very difficult.
34
Nikmesoft Ltd
NotificationCenter
 NotificationCenter
 Cons
• Third party object required to manage the link between controllers and
observer objects.
• Notification Names, and UserInfo dictionary keys need to be known by both
the observers and the controllers. If these are not defined in a common place,
they can very easily become out of sync.
• No ability for the controller to get any information back from an observer after
a notification is posted.
35
Nikmesoft Ltd
Example 4.2
36
ImageDownloader
Image URL + Key
Return UIImage
Nikmesoft Ltd
Exercise 4
37
Nikmesoft Ltd
Multiple Background Threads
GCD & NSOperations
38
Nikmesoft Ltd
GCD & NSOperations
 GCD
 Grand Central Dispatch, or GCD for short, is a C API that makes it
exceptionally easy to perform asynchronous operations in iOS.
 With GCD, you can line up blocks of code in a queue for the
system to execute as necessary. These blocks or operations, will
be dispatched in the queue to another thread, leaving your main
UI thread to continue its tasks.
39
Nikmesoft Ltd
GCD & NSOperations
 Queues
40
Serial
queue
Concurrent
queue
main
queue
global
queue
User
queue
Nikmesoft Ltd
GCD & NSOperations
 Concurrent Queue
41
Block 3 Block 2 Block 1 Block 3 Block 2 Block 1
Nikmesoft Ltd
GCD & NSOperations
 Concurrent Queue
42
Block 3 Block 2 Block 1
Nikmesoft Ltd
GCD & NSOperations
 Concurrent Queue
43
Block 3 Block 2 Block 1
Nikmesoft Ltd
GCD & NSOperations
 Serial Queue
44
Block 3 Block 2 Block 1 Block 3 Block 2 Block 1
Nikmesoft Ltd
GCD & NSOperations
 Serial Queue
45
Block 3 Block 2
Block 1
Nikmesoft Ltd
GCD & NSOperations
 Serial Queue
46
Block 3 Block 2
Block 1
Nikmesoft Ltd
GCD & NSOperations
 How to create a queue?
47
Nikmesoft Ltd
GCD & NSOperations
 Sync & Async
48
Block
UI Thread UI Thread
Sync
Nikmesoft Ltd
GCD & NSOperations
 Sync & Async
49
Block
UI Thread
ASync
Nikmesoft Ltd
GCD & NSOperations
 Demo code
50
Nikmesoft Ltd
GCD & NSOperations
 NSOperations
 GCD is a lightweight way to represent units of work that are going
to be executed concurrently. You don’t schedule these units of
work; the system takes care of scheduling for you. Adding
dependency among blocks can be a headache. Canceling or
suspending a block creates extra work for you as a developer!
51
Nikmesoft Ltd
GCD & NSOperations
 NSOperations
 NSOperation and NSOperationQueue add a little extra overhead
compared to GCD, but you can add dependency among various
operations. You can re-use operations, cancel or suspend them.
52
Nikmesoft Ltd
GCD & NSOperations
 Create a NSOperation
 Subclass NSOperation
 Override “main”
 Create an “autoreleasepool” in “main”
 Put your code within the “autoreleasepool”
53
Nikmesoft Ltd
GCD & NSOperations
 Create a NSOperation
54
Nikmesoft Ltd
GCD & NSOperations
 Important notes
 Dependency: you can make an operation dependent on other
operations. Any operation can be dependent on any number of
operations. When you make operation A dependent on operation
B, even though you call “start” on operation A, it will not start
unless operation B isFinished is true.
55
Nikmesoft Ltd
GCD & NSOperations
 Important notes
 Priority: sometimes the operation you wish to run in the
background is not crucial and can be performed at a lower priority.
You set the priority of an operation by using “setQueuePriority:”.
 Completion block: another useful method in NSOperation class
is setCompletionBlock:. If there is something that you want to do
once the operation has been completed, you can put it in a block
and pass it into this method. Note that there is no guarantee the
block will be executed on the main thread.
56
Nikmesoft Ltd
GCD & NSOperations
 Important notes
 Always check for the isCancelled property frequently. You don’t
want to run a operation in the background if it is no longer
required!
 You cannot reuse an operation. Once it is added to a queue, you
give up ownership. If you want to use the same operation class
again, you must create a new instance.
 A finished operation cannot be restarted.
57
Nikmesoft Ltd
GCD & NSOperations
 Important notes
 If you cancel an operation, it will not happen instantly. It will
happen at some point in the future when someone explicitly
checks for isCancelled == YES in “main”; otherwise, the operation
will run until it is done.
58
Nikmesoft Ltd
GCD & NSOperations
 NSOperationQueue
 Concurrent operations
 Maximum number of concurrent operations: you can set the
maximum number of operations that NSOperationQueue can run
concurrently. NSOperationQueue may choose to run any number
of concurrent operations, but it won’t be more than the maximum.
 Add operation
 Pending operations:
59
Nikmesoft Ltd
GCD & NSOperations
 NSOperationQueue
 Pending operations: at any time you can ask a queue which
operations are in the queue, and how many operations there are
in total. Remember that only those operations that are waiting to
be executed, and those that are running, are kept in the queue. As
soon as an operation is done, it is gone from the queue.
60
Nikmesoft Ltd
GCD & NSOperations
 NSOperationQueue
 Pause (suspend) queue: you can pause a queue by setting
setSuspended:YES. This will suspend all operations in a queue —
you can’t suspend operations individually. To resume the queue,
simply setSuspended:NO.
 Cancel operations: to cancel all operations in a queue, you
simply call “cancelAllOperations”. Do you remember earlier where
it was noted that your code should frequently check for
isCancelled property in NSOperation?
61
Nikmesoft Ltd
GCD & NSOperations
 NSOperationQueue
 addOperationWithBlock: if you have a simple operation that
does not need to be subclasses, you can simply pass it into a
queue by way of a block.
 [NSOperationQueuemainQueue]:
 NSInvocationOperation is a subclass of NSOperation which
allows you to specify a target and selector that will run as an
operation.
62
Nikmesoft Ltd
GCD & NSOperations
 NSOperationQueue
63
Nikmesoft Ltd
64

Weitere ähnliche Inhalte

Andere mochten auch

[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS ProgrammingNikmesoft Ltd
 
[iOS] Basic UI Elements
[iOS] Basic UI Elements[iOS] Basic UI Elements
[iOS] Basic UI ElementsNikmesoft Ltd
 
iOS Basics: Introducing the iPad, iPhone, and iCloud
iOS Basics: Introducing the iPad, iPhone, and iCloudiOS Basics: Introducing the iPad, iPhone, and iCloud
iOS Basics: Introducing the iPad, iPhone, and iCloudSt. Petersburg College
 
iOS: Overview, Architecture, Development & Versions
iOS: Overview, Architecture, Development & Versions iOS: Overview, Architecture, Development & Versions
iOS: Overview, Architecture, Development & Versions Sandra Kerbage
 
Linear Regression
Linear RegressionLinear Regression
Linear RegressionRyan Sain
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersRyanISI
 
Pentesting iOS Applications
Pentesting iOS ApplicationsPentesting iOS Applications
Pentesting iOS Applicationsjasonhaddix
 

Andere mochten auch (12)

[iOS] Navigation
[iOS] Navigation[iOS] Navigation
[iOS] Navigation
 
[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming[iOS] Introduction to iOS Programming
[iOS] Introduction to iOS Programming
 
[iOS] Basic UI Elements
[iOS] Basic UI Elements[iOS] Basic UI Elements
[iOS] Basic UI Elements
 
iOS Basics: Introducing the iPad, iPhone, and iCloud
iOS Basics: Introducing the iPad, iPhone, and iCloudiOS Basics: Introducing the iPad, iPhone, and iCloud
iOS Basics: Introducing the iPad, iPhone, and iCloud
 
iOS: Overview, Architecture, Development & Versions
iOS: Overview, Architecture, Development & Versions iOS: Overview, Architecture, Development & Versions
iOS: Overview, Architecture, Development & Versions
 
Linear Regression
Linear RegressionLinear Regression
Linear Regression
 
A seminar report on i cloud
A  seminar report on i cloudA  seminar report on i cloud
A seminar report on i cloud
 
iOS Application Penetration Testing
iOS Application Penetration TestingiOS Application Penetration Testing
iOS Application Penetration Testing
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
Pentesting iOS Applications
Pentesting iOS ApplicationsPentesting iOS Applications
Pentesting iOS Applications
 
Ios operating system
Ios operating systemIos operating system
Ios operating system
 
Apple iOS
Apple iOSApple iOS
Apple iOS
 

Ähnlich wie Nikmesoft Multiple Background Thread Techniques

04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slotsmha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slotsmha4
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingPatricia Viljoen
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3Diane Allen
 
Journey from Monolith to a Modularized Application - Approach and Key Learnin...
Journey from Monolith to a Modularized Application - Approach and Key Learnin...Journey from Monolith to a Modularized Application - Approach and Key Learnin...
Journey from Monolith to a Modularized Application - Approach and Key Learnin...mfrancis
 
PThreads Vs Win32 Threads
PThreads  Vs  Win32 ThreadsPThreads  Vs  Win32 Threads
PThreads Vs Win32 ThreadsRobert Sayegh
 
Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012
Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012
Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012TEST Huddle
 
SDN Demystified, by Dean Pemberton [APNIC 38]
SDN Demystified, by Dean Pemberton [APNIC 38]SDN Demystified, by Dean Pemberton [APNIC 38]
SDN Demystified, by Dean Pemberton [APNIC 38]APNIC
 
Threading Programming Guide
Threading Programming GuideThreading Programming Guide
Threading Programming GuideDEVTYPE
 
how-to-bypass-AM-PPL
how-to-bypass-AM-PPLhow-to-bypass-AM-PPL
how-to-bypass-AM-PPLnitinscribd
 
Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...
Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...
Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...Ambassador Labs
 
Disadvantages Of Robotium
Disadvantages Of RobotiumDisadvantages Of Robotium
Disadvantages Of RobotiumSusan Tullis
 
Software Define Network, a new security paradigm ?
Software Define Network, a new security paradigm ?Software Define Network, a new security paradigm ?
Software Define Network, a new security paradigm ?Jean-Marc ANDRE
 
SDN - a new security paradigm?
SDN - a new security paradigm?SDN - a new security paradigm?
SDN - a new security paradigm?Sophos Benelux
 
IRJET- Development of Uncrackable Software
IRJET- Development of Uncrackable SoftwareIRJET- Development of Uncrackable Software
IRJET- Development of Uncrackable SoftwareIRJET Journal
 
Centralized monitoring station for it computing and network infrastructure1
Centralized monitoring station for it computing and network infrastructure1Centralized monitoring station for it computing and network infrastructure1
Centralized monitoring station for it computing and network infrastructure1MOHD ARISH
 
Linux Operating System Resembles Unix Operating. System
Linux Operating System Resembles Unix Operating. SystemLinux Operating System Resembles Unix Operating. System
Linux Operating System Resembles Unix Operating. SystemOlga Bautista
 

Ähnlich wie Nikmesoft Multiple Background Thread Techniques (20)

04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Linux Assignment 3
Linux Assignment 3Linux Assignment 3
Linux Assignment 3
 
New204
New204New204
New204
 
Journey from Monolith to a Modularized Application - Approach and Key Learnin...
Journey from Monolith to a Modularized Application - Approach and Key Learnin...Journey from Monolith to a Modularized Application - Approach and Key Learnin...
Journey from Monolith to a Modularized Application - Approach and Key Learnin...
 
PThreads Vs Win32 Threads
PThreads  Vs  Win32 ThreadsPThreads  Vs  Win32 Threads
PThreads Vs Win32 Threads
 
Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012
Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012
Mike Bartley - Innovations for Testing Parallel Software - EuroSTAR 2012
 
SDN Demystified, by Dean Pemberton [APNIC 38]
SDN Demystified, by Dean Pemberton [APNIC 38]SDN Demystified, by Dean Pemberton [APNIC 38]
SDN Demystified, by Dean Pemberton [APNIC 38]
 
Tos tutorial
Tos tutorialTos tutorial
Tos tutorial
 
Threading Programming Guide
Threading Programming GuideThreading Programming Guide
Threading Programming Guide
 
how-to-bypass-AM-PPL
how-to-bypass-AM-PPLhow-to-bypass-AM-PPL
how-to-bypass-AM-PPL
 
Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...
Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...
Montreal Kubernetes Meetup: Developer-first workflows (for microservices) on ...
 
Lab6 rtos
Lab6 rtosLab6 rtos
Lab6 rtos
 
Disadvantages Of Robotium
Disadvantages Of RobotiumDisadvantages Of Robotium
Disadvantages Of Robotium
 
Software Define Network, a new security paradigm ?
Software Define Network, a new security paradigm ?Software Define Network, a new security paradigm ?
Software Define Network, a new security paradigm ?
 
SDN - a new security paradigm?
SDN - a new security paradigm?SDN - a new security paradigm?
SDN - a new security paradigm?
 
IRJET- Development of Uncrackable Software
IRJET- Development of Uncrackable SoftwareIRJET- Development of Uncrackable Software
IRJET- Development of Uncrackable Software
 
Centralized monitoring station for it computing and network infrastructure1
Centralized monitoring station for it computing and network infrastructure1Centralized monitoring station for it computing and network infrastructure1
Centralized monitoring station for it computing and network infrastructure1
 
Linux Operating System Resembles Unix Operating. System
Linux Operating System Resembles Unix Operating. SystemLinux Operating System Resembles Unix Operating. System
Linux Operating System Resembles Unix Operating. System
 

Mehr von Nikmesoft Ltd

[Android] Multimedia Programming
[Android] Multimedia Programming[Android] Multimedia Programming
[Android] Multimedia ProgrammingNikmesoft Ltd
 
[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android AnimationNikmesoft Ltd
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D GraphicsNikmesoft Ltd
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast ReceiversNikmesoft Ltd
 
[Android] Web services
[Android] Web services[Android] Web services
[Android] Web servicesNikmesoft Ltd
 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background ThreadsNikmesoft Ltd
 
[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based Services[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based ServicesNikmesoft Ltd
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data StorageNikmesoft Ltd
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and ActivityNikmesoft Ltd
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event HandlingNikmesoft Ltd
 
[Android] Using Selection Widgets
[Android] Using Selection Widgets[Android] Using Selection Widgets
[Android] Using Selection WidgetsNikmesoft Ltd
 
[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers[Android] Basic Widgets and Containers
[Android] Basic Widgets and ContainersNikmesoft Ltd
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android ProgrammingNikmesoft Ltd
 

Mehr von Nikmesoft Ltd (13)

[Android] Multimedia Programming
[Android] Multimedia Programming[Android] Multimedia Programming
[Android] Multimedia Programming
 
[Android] Android Animation
[Android] Android Animation[Android] Android Animation
[Android] Android Animation
 
[Android] 2D Graphics
[Android] 2D Graphics[Android] 2D Graphics
[Android] 2D Graphics
 
[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers[Android] Services and Broadcast Receivers
[Android] Services and Broadcast Receivers
 
[Android] Web services
[Android] Web services[Android] Web services
[Android] Web services
 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background Threads
 
[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based Services[Android] Maps, Geocoding and Location-Based Services
[Android] Maps, Geocoding and Location-Based Services
 
[Android] Data Storage
[Android] Data Storage[Android] Data Storage
[Android] Data Storage
 
[Android] Intent and Activity
[Android] Intent and Activity[Android] Intent and Activity
[Android] Intent and Activity
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event Handling
 
[Android] Using Selection Widgets
[Android] Using Selection Widgets[Android] Using Selection Widgets
[Android] Using Selection Widgets
 
[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers[Android] Basic Widgets and Containers
[Android] Basic Widgets and Containers
 
[Android] Introduction to Android Programming
[Android] Introduction to Android Programming[Android] Introduction to Android Programming
[Android] Introduction to Android Programming
 

Nikmesoft Multiple Background Thread Techniques

  • 2. Nikmesoft Ltd Contents 2 Overview1 NSThread & NSRunLoop2 Blocks & NotificationCenter3 GCD & NSOperations4 Exercise 45
  • 4. Nikmesoft Ltd Overview  When an application is launched, the system creates a thread of execution for the application, called "main."  The main thread is also sometimes called the UI thread.  The system does not create a separate thread for each instance of a component. All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. 4
  • 5. Nikmesoft Ltd Overview  If everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI.  When the thread is blocked, no events can be dispatched, including drawing events. 5
  • 6. Nikmesoft Ltd Overview  Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog (Android) 6
  • 7. Nikmesoft Ltd Overview  The user might then decide to quit your application and uninstall it if they are unhappy. 7
  • 8. Nikmesoft Ltd Overview  There are simply two rules to single thread model:  Do not block the UI thread  Do not access the UI toolkit from outside the UI thread 8
  • 9. Nikmesoft Ltd Overview  Having multiple threads in an application provides two very important potential advantages:  Multiple threads can improve an application’s perceived responsiveness.  Multiple threads can improve an application’s real-time performance on multicore systems. 9
  • 10. Nikmesoft Ltd Multiple Background Threads NSThread & NSRunloop 10
  • 11. Nikmesoft Ltd NSThread & NSRunloop  Create new Thread  [NSThread detachNewThreadSelector:@selector(startTheBackgro undJob) toTarget:self withObject:nil];  Create subclass of NSThread and override main method  Run on UI Thread  [self performSelectorOnMainThread:@selector(updateUI) withObj ect:nil waitUntilDone:NO]; 11
  • 12. Nikmesoft Ltd NSThread & NSRunloop  The problem  Touches aren’t the only source of input to an iPhone application. Ex socket listening  But you don’t want the UI to lock up whilst it’s listening – you still want input from the user to be dealt with promptly.  Similarly, you might want events to be triggered automatically at certain time intervals, but without locking up the application in the interim. 12
  • 13. Nikmesoft Ltd NSThread & NSRunloop  The Solution  Using a separate thread  NSRunLoop 13
  • 14. Nikmesoft Ltd NSThread & NSRunloop  NSRunLoop  A run loop is an abstraction that (among other things) provides a mechanism to handle system input sources (sockets, ports, files, keyboard, mouse, timers, etc).  Each NSThread has its own run loop, which can be accessedvia the currentRunLoop method.  A run loop for a given thread will wait until one or more of its input sources has some data or event, then fire the appropriate input handler(s) to process each input source that is "ready.". 14
  • 15. Nikmesoft Ltd NSThread & NSRunloop  NSRunLoop  After doing so, it will then return to its loop, processing input from various sources, and "sleeping" if there is no work to do. 15
  • 16. Nikmesoft Ltd NSThread & NSRunloop 16 Design Tips  Avoid Creating Threads Explicitly  Keep Your Threads Reasonably Busy  Avoid Shared Data Structures  Terminate Your Threads Cleanly
  • 19. Nikmesoft Ltd Blocks  Blocks  Blocks are Objective-C’s anonymous functions.  Function and function pointer  Creating Blocks  Blocks use all the same mechanics as normal functions. You can declare a block variable just like you would declare a function, define the block as though you would implement a function, and then call the block as if it were a function: 19
  • 21. Nikmesoft Ltd Blocks  Blocks as Method Parameters  Storing blocks in variables is occasionally useful, but in the real world, they’re more likely to be used as method parameters. They solve the same problem as function pointers, but the fact that they can be defined inline makes the resulting code much easier to read. 21
  • 22. Nikmesoft Ltd Blocks  Blocks as Method Parameters 22
  • 23. Nikmesoft Ltd Blocks  Defining Block Types  Storing blocks in variables is occasionally useful, but in the real world, they’re more likely to be used as method parameters. They solve the same problem as function pointers, but the fact that they can be defined inline makes the resulting code much easier to read. 23
  • 25. Nikmesoft Ltd Multiple Background Threads NotificationCenter 25
  • 26. Nikmesoft Ltd NotificationCenter  NSNotificationCenter  NSNotificationCenter is one way you can communicate with other objects in your project.  Post and receive a notification 26
  • 27. Nikmesoft Ltd NotificationCenter  Post and receive a notification 27
  • 28. Nikmesoft Ltd NotificationCenter  Post and receive a notification 28
  • 29. Nikmesoft Ltd NotificationCenter  Why we need to use NSNotificationCenter  Delegation  Notification Center  Key value observing(KVO) 29
  • 30. Nikmesoft Ltd NotificationCenter  Delegation  Pros • Ability to have multiple protocols defined one controller, each with different delegates. • No third party object required to maintain / monitor the communication process. • Ability to receive a returned value from a called protocol method. This means that a delegate can help provide information back to a controller 30
  • 31. Nikmesoft Ltd NotificationCenter  Delegation  Pros • Very strict syntax. All events to be heard are clearly defined in the delegate protocol. • Compile time Warnings / Errors if a method is not implemented as it should be by a delegate. • Protocol defined within the scope of the controller only. • Very traceable, and easy to identify flow of control within an application. 31
  • 32. Nikmesoft Ltd NotificationCenter  Delegation  Cons • Many lines of code required to define: 1. the protocol definition, 2. the delegate property in the controller, and 3. the implementation of the delegate method definitions within the delegate itself. • Although possible, it can be difficult and the pattern does not really lend itself to have multiple delegates of the same protocol in a controller (telling multiple objects about the same event) 32
  • 33. Nikmesoft Ltd NotificationCenter  NotificationCenter  Pros • Easy to implement, with not many lines of code. • Can easily have multiple objects reacting to the same notification being posted. • Controller can pass in a context (dictionary) object with custom information (userInfo) related to the notification being posted. 33
  • 34. Nikmesoft Ltd NotificationCenter  NotificationCenter  Cons • No compile time to checks to ensure that notifications are correctly handled by observers. • Required to un-register with the notification center if your previously registered object is deallocated. • Not very traceable. Attempting to debug issues related to application flow and control can be very difficult. 34
  • 35. Nikmesoft Ltd NotificationCenter  NotificationCenter  Cons • Third party object required to manage the link between controllers and observer objects. • Notification Names, and UserInfo dictionary keys need to be known by both the observers and the controllers. If these are not defined in a common place, they can very easily become out of sync. • No ability for the controller to get any information back from an observer after a notification is posted. 35
  • 38. Nikmesoft Ltd Multiple Background Threads GCD & NSOperations 38
  • 39. Nikmesoft Ltd GCD & NSOperations  GCD  Grand Central Dispatch, or GCD for short, is a C API that makes it exceptionally easy to perform asynchronous operations in iOS.  With GCD, you can line up blocks of code in a queue for the system to execute as necessary. These blocks or operations, will be dispatched in the queue to another thread, leaving your main UI thread to continue its tasks. 39
  • 40. Nikmesoft Ltd GCD & NSOperations  Queues 40 Serial queue Concurrent queue main queue global queue User queue
  • 41. Nikmesoft Ltd GCD & NSOperations  Concurrent Queue 41 Block 3 Block 2 Block 1 Block 3 Block 2 Block 1
  • 42. Nikmesoft Ltd GCD & NSOperations  Concurrent Queue 42 Block 3 Block 2 Block 1
  • 43. Nikmesoft Ltd GCD & NSOperations  Concurrent Queue 43 Block 3 Block 2 Block 1
  • 44. Nikmesoft Ltd GCD & NSOperations  Serial Queue 44 Block 3 Block 2 Block 1 Block 3 Block 2 Block 1
  • 45. Nikmesoft Ltd GCD & NSOperations  Serial Queue 45 Block 3 Block 2 Block 1
  • 46. Nikmesoft Ltd GCD & NSOperations  Serial Queue 46 Block 3 Block 2 Block 1
  • 47. Nikmesoft Ltd GCD & NSOperations  How to create a queue? 47
  • 48. Nikmesoft Ltd GCD & NSOperations  Sync & Async 48 Block UI Thread UI Thread Sync
  • 49. Nikmesoft Ltd GCD & NSOperations  Sync & Async 49 Block UI Thread ASync
  • 50. Nikmesoft Ltd GCD & NSOperations  Demo code 50
  • 51. Nikmesoft Ltd GCD & NSOperations  NSOperations  GCD is a lightweight way to represent units of work that are going to be executed concurrently. You don’t schedule these units of work; the system takes care of scheduling for you. Adding dependency among blocks can be a headache. Canceling or suspending a block creates extra work for you as a developer! 51
  • 52. Nikmesoft Ltd GCD & NSOperations  NSOperations  NSOperation and NSOperationQueue add a little extra overhead compared to GCD, but you can add dependency among various operations. You can re-use operations, cancel or suspend them. 52
  • 53. Nikmesoft Ltd GCD & NSOperations  Create a NSOperation  Subclass NSOperation  Override “main”  Create an “autoreleasepool” in “main”  Put your code within the “autoreleasepool” 53
  • 54. Nikmesoft Ltd GCD & NSOperations  Create a NSOperation 54
  • 55. Nikmesoft Ltd GCD & NSOperations  Important notes  Dependency: you can make an operation dependent on other operations. Any operation can be dependent on any number of operations. When you make operation A dependent on operation B, even though you call “start” on operation A, it will not start unless operation B isFinished is true. 55
  • 56. Nikmesoft Ltd GCD & NSOperations  Important notes  Priority: sometimes the operation you wish to run in the background is not crucial and can be performed at a lower priority. You set the priority of an operation by using “setQueuePriority:”.  Completion block: another useful method in NSOperation class is setCompletionBlock:. If there is something that you want to do once the operation has been completed, you can put it in a block and pass it into this method. Note that there is no guarantee the block will be executed on the main thread. 56
  • 57. Nikmesoft Ltd GCD & NSOperations  Important notes  Always check for the isCancelled property frequently. You don’t want to run a operation in the background if it is no longer required!  You cannot reuse an operation. Once it is added to a queue, you give up ownership. If you want to use the same operation class again, you must create a new instance.  A finished operation cannot be restarted. 57
  • 58. Nikmesoft Ltd GCD & NSOperations  Important notes  If you cancel an operation, it will not happen instantly. It will happen at some point in the future when someone explicitly checks for isCancelled == YES in “main”; otherwise, the operation will run until it is done. 58
  • 59. Nikmesoft Ltd GCD & NSOperations  NSOperationQueue  Concurrent operations  Maximum number of concurrent operations: you can set the maximum number of operations that NSOperationQueue can run concurrently. NSOperationQueue may choose to run any number of concurrent operations, but it won’t be more than the maximum.  Add operation  Pending operations: 59
  • 60. Nikmesoft Ltd GCD & NSOperations  NSOperationQueue  Pending operations: at any time you can ask a queue which operations are in the queue, and how many operations there are in total. Remember that only those operations that are waiting to be executed, and those that are running, are kept in the queue. As soon as an operation is done, it is gone from the queue. 60
  • 61. Nikmesoft Ltd GCD & NSOperations  NSOperationQueue  Pause (suspend) queue: you can pause a queue by setting setSuspended:YES. This will suspend all operations in a queue — you can’t suspend operations individually. To resume the queue, simply setSuspended:NO.  Cancel operations: to cancel all operations in a queue, you simply call “cancelAllOperations”. Do you remember earlier where it was noted that your code should frequently check for isCancelled property in NSOperation? 61
  • 62. Nikmesoft Ltd GCD & NSOperations  NSOperationQueue  addOperationWithBlock: if you have a simple operation that does not need to be subclasses, you can simply pass it into a queue by way of a block.  [NSOperationQueuemainQueue]:  NSInvocationOperation is a subclass of NSOperation which allows you to specify a target and selector that will run as an operation. 62
  • 63. Nikmesoft Ltd GCD & NSOperations  NSOperationQueue 63