DOC PREVIEW
UMD CMSC 330 - Threads

This preview shows page 1-2-3-24-25-26 out of 26 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 26 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

CMSC 330: Organization ofProgramming LanguagesThreadsCMSC 330 2Computation AbstractionsCPU 1 CPU 2p3p1 p2 p4t1t2t1t2t3t1t4t5A computerProcesses(e.g., JVM’s)ThreadsCMSC 330 3Processes vs. Threadsint x;foo() {…x…}int x;foo() {…x…}int x;foo() { …x…}foo() { …x…}Processes do notshare dataThreads share datawithin a processCMSC 330 4So, What Is a Thread?• Conceptually: it is a parallel computationoccurring within a process• Implementation view: it’s a program counterand a stack. The heap and static area areshared among all threads• All programs have at least one thread (main)CMSC 330 5Implementation View• Per-thread stack and instruction pointer– Saved in memory when thread suspended– Put in hardware esp/eip when thread resumeseipeipeipespespespCMSC 330 6Tradeoffs• Threads can increase performance– Parallelism on multiprocessors– Concurrency of computation and I/O• Natural fit for some programming patterns– Event processing– Simulations• But increased complexity– Need to worry about safety, liveness, composition• And higher resource usageCMSC 330 7Programming Threads• Threads are available in many languages– C, C++, Objective Caml, Java, SmallTalk …• In many languages (e.g., C and C++), threadsare a platform specific add-on– Not part of the language specification• They're part of the Java language specificationCMSC 330 8Java Threads• Every application has at least one thread– The “main” thread, started by the JVM to run theapplication’s main() method• main() can create other threads– Explicitly, using the Thread class– Implicitly, by calling libraries that create threads as aconsequence• RMI, AWT/Swing, Applets, etc.CMSC 330 9Thread Creationexecution (time)main threadthread startsthread startsthread endsthreadjoinCMSC 330 10Thread Creation in Java• 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() methodconcurrently with the current thread– Thread terminates when its run() method returnsCMSC 330 11Running Example: Alarms• Goal: let's set alarms which will be triggered inthe future– Input: time t (seconds) and message m– Result: we’ll see m printed after t secondsCMSC 330 12Example: Synchronous alarmswhile (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);}CMSC 330 13Making 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); }}CMSC 330 14Making 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(); }}CMSC 330 15Alternative: 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)CMSC 330 16Thread Example Revisitedpublic 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); }}CMSC 330 17Thread 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(); }}CMSC 330 18Notes: Passing Parameters• run() doesn’t take parameters• We “pass parameters” to the new thread bystoring them as private fields– In the extended class– Or the Runnable object– Example: the time to wait and the message to print inthe AlarmThread classCMSC 330 19Concurrency• A concurrent program is one that has multiplethreads that may be active at the same time– Might run on one CPU• The CPU alternates between running different threads• The scheduler takes care of the details– Switching between threads might happen at any time– Might run in parallel on a multiprocessor machine• One with more than one CPU• May have multiple threads per CPU• Multiprocessor machines are becoming morecommon– Multi-CPU machines aren't that expensive any more– Dual-core CPUs are available nowCMSC 330 20Scheduling Example (1)CPU 1CPU 2p1p2p1p2One process per CPUp2 threads:p1 threads:CMSC 330 21Scheduling Example (2)CPU 1CPU 2p1p2p1p2Threads shared between CPU’sp2 threads:p1 threads:CMSC 330 22Concurrency and Shared Data• Concurrency is easy if threads don’t interact– Each thread does its own thing, ignoring other threads– Typically, however, threads need to communicate witheach other• Communication is done by sharing data– In Java, different threads may access the heapsimultaneously– But the scheduler might interleave threads arbitrarily– Problems can occur if we’re not careful.CMSC 330 23Data Race Examplepublic class Example extends Thread { private static int cnt = 0; // shared state public void run() { int y = cnt; cnt = y + 1; } public static void main(String args[]) { Thread t1 = new Example(); Thread t2 = new Example(); t1.start(); t2.start(); }}CMSC 330 24Data Race Examplestatic int cnt = 0;t1.run() { int y = cnt; cnt = y + 1;}t2.run() { int y = cnt; cnt = y + 1;}cnt = 0Start: both threads ready torun. Each will increment theglobal cnt. Shared stateCMSC 330 25Data Race Examplestatic int cnt = 0;t1.run() { int y = cnt; cnt = y + 1;}t2.run() { int y = cnt; cnt = y + 1;}cnt = 0T1 executes, grabbingthe global counter value intoits own y.Shared statey = 0CMSC 330 26Data Race Examplestatic int cnt = 0;t1.run() { int y = cnt; cnt = y +


View Full Document

UMD CMSC 330 - Threads

Documents in this Course
Exam #1

Exam #1

6 pages

Quiz #1

Quiz #1

2 pages

Midterm 2

Midterm 2

12 pages

Exam #2

Exam #2

7 pages

Ocaml

Ocaml

7 pages

Parsing

Parsing

38 pages

Threads

Threads

12 pages

Ruby

Ruby

7 pages

Quiz #3

Quiz #3

2 pages

Threads

Threads

7 pages

Quiz #4

Quiz #4

2 pages

Exam #2

Exam #2

6 pages

Exam #1

Exam #1

6 pages

Threads

Threads

34 pages

Quiz #4

Quiz #4

2 pages

Exam #2

Exam #2

9 pages

Exam #2

Exam #2

6 pages

Load more
Download Threads
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Threads and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Threads 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?