2/20/2016 EEC492/693/793 - iPhone Application Development 12/20/2016 EEC492/693/793 - iPhone Application Development 1 EEC-492/693/793 iPhone Application.

Slides:



Advertisements
Similar presentations
How to Build Multi- threaded Applications in.NET Mazen S. Alzogbi Technology Specialist Microsoft Corporation.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 5 Threads os5.
Computer Systems/Operating Systems - Class 8
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
Multithreading The objectives of this chapter are:
Chapter 5 Processes and Threads Copyright © 2008.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
3.5 Interprocess Communication Many operating systems provide mechanisms for interprocess communication (IPC) –Processes must communicate with one another.
5.6.2 Thread Synchronization with Semaphores Semaphores can be used to notify other threads that events have occurred –Producer-consumer relationship Producer.
3.5 Interprocess Communication
Threads CSCI 444/544 Operating Systems Fall 2008.
Concurrency, Threads, and Events Robbert van Renesse.
Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Austin Java Users Group developerWorks article – µActor Library BARRY FEIGENBAUM, PH. D. 02/26/13.
1 Lecture 4: Threads Operating System Fall Contents Overview: Processes & Threads Benefits of Threads Thread State and Operations User Thread.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
CSE 425: Concurrency III Monitors A monitor is a higher level construct for synchronizing multiple threads’ access to a common code segment –Can implement.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
The University of Adelaide, School of Computer Science
Getting Started with the µC/OS-III Real Time Kernel Akos Ledeczi EECE 6354, Fall 2015 Vanderbilt University.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Internet Software Development Controlling Threads Paul J Krause.
Concurrency Design Patterns
Copyright ©: University of Illinois CS 241 Staff1 Threads Systems Concepts.
Lecture 8 Page 1 CS 111 Online Other Important Synchronization Primitives Semaphores Mutexes Monitors.
Chapter 6 – Process Synchronisation (Pgs 225 – 267)
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Lecture 5: Threads process as a unit of scheduling and a unit of resource allocation processes vs. threads what to program with threads why use threads.
Department of Computer Science and Software Engineering
C H A P T E R E L E V E N Concurrent Programming Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan.
Lecture 6 Page 1 CS 111 Summer 2013 Concurrency Solutions and Deadlock CS 111 Operating Systems Peter Reiher.
4.1 Introduction to Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads.
3/12/2013Computer Engg, IIT(BHU)1 OpenMP-1. OpenMP is a portable, multiprocessing API for shared memory computers OpenMP is not a “language” Instead,
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer.
pThread synchronization
Pitfalls: Time Dependent Behaviors CS433 Spring 2001 Laxmikant Kale.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
Concepts of Multithreading CS 378 – Mobile Computing for iOS Dr. William C. Bulko.
Multithreading The objectives of this chapter are:
Chapter 3: Windows7 Part 5.
Multi Threading.
Background on the need for Synchronization
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Outline Other synchronization primitives
Other Important Synchronization Primitives
Computer Engg, IIT(BHU)
Getting Started with the µC/OS-III Real Time Kernel
Threads and Cooperation
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Chapter 3: Windows7 Part 5.
Multithreaded Programming
Threaded Programming in Python
CSCI1600: Embedded and Real Time Software
CSCI1600: Embedded and Real Time Software
Multithreading The objectives of this chapter are:
CMSC 202 Threads.
Ch 3.
More concurrency issues
Presentation transcript:

2/20/2016 EEC492/693/793 - iPhone Application Development 12/20/2016 EEC492/693/793 - iPhone Application Development 1 EEC-492/693/793 iPhone Application Development Lecture 22 Concurrency and Multithreading (slides based on CS193P, Stanford) Wenbing Zhao & Nigamanth Sridhar

Concurrency With only one thread, long-running operations can interfere with user interaction  System can’t update the screen  App looks like it’s hung Multiple threads allow multiple computations without locking up your entire application  Blocking operation can happen on the background thread 2/20/2016 EEC492/693/793 - iPhone Application Development 2

Threads on iPhone Based on POSIX threads API  /usr/include/pthread.h Higher-level wrappers in Foundation framework  NSThread  Object-oriented, easy to use 2/20/2016 EEC492/693/793 - iPhone Application Development 3

NSThread Run loop automatically instantiated for each thread  Run loop is the main event loop that the app runs  App spends most of its time in the run loop Each NSThread needs to create its own autorelease pool  One is not created for you Includes methods for inter-thread messaging 2/20/2016 EEC492/693/793 - iPhone Application Development 4

NSThread Creating a new thread  Attach a selector to the new thread The selector method does the actual work Once the work is complete, the selector on the background thread sends a message back to the main thread to notify completion  All interaction with the user must happen on the main thread 2/20/2016 EEC492/693/793 - iPhone Application Development 5

Using NSThread 2/20/2016 EEC492/693/793 - iPhone Application Development 6 - (void)someAction:(id)sender { // Fire up new thread [NSThread withTarget:self object:someData]; } - (void)doWork:(id)someData { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [someData doLotsOfWork]; // Send message back to main thread [self withObject:[someData result] waitUntilDone:NO]; [pool release]; }

Dangers of Multiple Threads Can add considerable amount of complexity to app design Threads share memory; they have access to the same data structures Need coordination to decide which thread has access to a particular data structure at a particular time  Synchronization and Locking 2/20/2016 EEC492/693/793 - iPhone Application Development 7

UIKit and Threadsafety Threadsafety  A single data object accessed in two different threads may lead to a race condition UIKit classes are not threadsafe  Objects must be created and messaged from the main thread Notable exception: UIImage can be created in a background thread  But since UIImageView is not threadsafe, you can’t set it in a background thread 2/20/2016 EEC492/693/793 - iPhone Application Development 8

Locks Protect critical sections of code Thread-safety NSLock 2/20/2016 EEC492/693/793 - iPhone Application Development 9 - (void)init { myLock = [[NSLock alloc] init]; } - (void)someMethod { [myLock lock]; // Execute critical section code [myLock unlock]; }

Conditions NSCondition is useful for producer/consumer model 2/20/2016 EEC492/693/793 - iPhone Application Development 10 // On the producer thread - (void) produceData { [condition lock]; // Produce new data newDataExists = YES; [condition signal]; [condition unlock]; } // On the consumer thread - (void) consumeData { [condition lock]; while(!newDataExists) { [condition wait]; } // Consume the new data newDataExists = NO; [condition unlock]; }

Danger of Locks Very easy to make mistakes All it takes is one “poorly behaved” client  Accessing shared data outside of a lock  Deadlocks  Priority inversion Main thread is always supposed to have highest priority 2/20/2016 EEC492/693/793 - iPhone Application Development 11

Threading Pitfalls Subtle, nondeterministic bugs may be introduced  Notoriously difficult to replicate Code may become more difficult to maintain Poorly managed threads and synchronization may actually result in slower code 2/20/2016 EEC492/693/793 - iPhone Application Development 12

Alternatives to Explicit Threading Asynchronous (nonblocking) functions  Call a function, and pass a pointer to a callback function  Specify a target/action or a delegate for callback Timers  One-shot or recurring  Specify a callback method  Managed by the run loop NSOperation: higher level construct 2/20/2016 EEC492/693/793 - iPhone Application Development 13

NSOperation Manages thread creation and lifecycle Encapsulate a unit of work in an object  System can schedule the operation when it is appropriate Specify priorities and dependencies 2/20/2016 EEC492/693/793 - iPhone Application Development 14

Creating an NSOperation Subclass Define a custom init method Override main method 2/20/2016 EEC492/693/793 - iPhone Application Development 15 - (id)initWithSomeObject:(id)someObject { self = [super init]; if (self) { self.someObject = someObject; } return self; } - (void)main { [someObject doLotsOfTimeConsumingWork]; }

NSOperationQueue Operations are typically scheduled by adding to a queue Choose a maximum number of concurrent operations  Runtime worries about creating an appropriate number of threads Queue runs operations based on priority and dependencies 2/20/2016 EEC492/693/793 - iPhone Application Development 16

NSInvocationOperation Concrete subclass of NSOperation For lightweight tasks 2/20/2016 EEC492/693/793 - iPhone Application Development 17 - (void)someAction:(id)sender { NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self object:someObject]; [queue addOperation:operation]; [operation release]; }