1 CMSC 433 – Programming Language Technologies and Paradigms Spring 2009 Threads and Synchronization (thanks to Doug Lea for some slides) 2 Overview • What are threads? – Concept – Basic Java mechanisms • Thread concerns – Safety and Liveness – Use of synchronization and signaling • Threading design patterns2 3 Computation Abstractions CPU 1 CPU 2 p3 p1 p2 p4 t1 t2 t1 t2 t3 t1 t4 t5 A computer Processes (e.g., JVM’s) Threads 4 Processes vs. Threads int x; foo() { …x… } int x; foo() { …x… } int x; foo() { …x… } foo() { …x… } Processes do not share data Threads share data within a process3 5 So, What Is a Thread? • Conceptually: it is a parallel computation occurring within a process • Implementation view: it’s a program counter and a stack. The heap and static area are shared among all threads • All programs have at least one thread (main) 6 Why Multiple Threads? • Performance: – Parallelism on multiprocessors – Concurrency of computation and I/O • Can easily express some programming paradigms – Event processing – Simulations • Keep computations separate, as in an OS – But - why not use processes?4 7 Why Not Multiple Threads? • Complexity: – Dealing with safety, liveness, composition – The root of the problem is shared state • Overhead – Higher resource usage – May limit performance compared to direct event processing • context switching, locking, etc. 8 Programming Threads • Threads are available in many languages – C, C++, Objective Caml, Java, SmallTalk … • In many languages (e.g., C and C++), threads are a platform specific add-on – Not part of the language specification • Part of the Java language specification5 9 Java Threads • Every application has at least one thread – The “main” thread, started by the JVM to run the application’s main() method • The code executed by main() can create other threads – Explicitly, using the Thread class – Implicitly, by calling libraries that create threads as a consequence • RMI, AWT/Swing, Applets, etc. 10 Java Threads: Creation • To explicitly create a thread – Instantiate a Thread object • An object of class Thread or a subclass of Thread – Invoke the object’s start() method • This will start executing the Thread’s run() method concurrently with the current thread – Thread terminates when its run() method returns6 11 Java Threads: Creation app thread main start run new 12 Running Example: Alarms • Goal: let us set alarms that will be triggered in the future – Input: Time t (seconds) and message m – Result: We’ll see m printed after t seconds7 13 Example: Synchronous alarms while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); // sets timeout // wait (in secs) try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); } 14 Making It Threaded (1) public class AlarmThread extends Thread { private String msg = null; private int timeout = 0; public AlarmThread(String msg, int time) { this.msg = msg; this.timeout = time; } public void run() { try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); } }8 15 Making It Threaded (2) while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); if (m != null) { // start alarm thread Thread t = new AlarmThread(m,tm); t.start(); } } 16 Alternative: The Runnable Interface • Extending Thread prohibits a different parent • Instead implement Runnable – Declares that the class has a void run() method • Construct a Thread from the Runnable – Constructor Thread(Runnable target) – Constructor Thread(Runnable target, String name)9 17 Thread Example Revisited public class AlarmRunnable implements Runnable { private String msg = null; private int timeout = 0; public AlarmRunnable(String msg, int time) { this.msg = msg; this.timeout = time; } public void run() { try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); } } 18 Thread Example Revisited (2) while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); if (m != null) { // start alarm thread Thread t = new Thread( new AlarmRunnable(m,tm)); t.start(); } }10 19 Notes: Passing Parameters • run() doesn’t take parameters • We “pass parameters” to the new thread by storing them as private fields – In the extended class – Or in the Runnable object – Example: the time to wait and the message to print in the AlarmThread class 20 Thread Scheduling • Once a new thread is created, how does it interact with existing threads? • This is a question of scheduling: – Given N processors and M threads, which thread(s) should be run at any given time?11 21 Thread Scheduling • OS schedules a single-threaded process on a single processor • Multithreaded process scheduling: – One thread per processor • Effectively splits a process across CPU’s • Exploits hardware-level concurrency – Many threads per processor • Need to share CPU in slices of time 22 Scheduling Example (1) CPU 1 CPU 2 p1 p2 p1 p2 One process per CPU p2 threads: p1 threads:12 23 Scheduling Example (2) CPU 1 CPU 2 p1 p2 p1 p2 Threads shared between CPU’s p2 threads: p1 threads: 24 Scheduling Consequences • Concurrency – Different threads from the same application can be running at the same time on different processors • Interleaving – Threads can be pre-empted at any time in order to schedule other threads13 25 Thread Scheduling • When multiple threads share a CPU, must decide: – When the current thread should stop running – What thread to run next • A thread can voluntarily yield() the CPU – Call to yield may be ignored; don’t depend on it • Preemptive schedulers can de-schedule the current thread at any time – Not all JVMs use preemptive scheduling, so a thread stuck in
View Full Document