CMSC 330: Organization of Programming Languages Threads.

Slides:



Advertisements
Similar presentations
Concurrent Programming Abstraction & Java Threads
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
CMSC 330: Organization of Programming Languages Concurrency / Multiprocessing.
1 CSC321 §2 Concurrent Programming Abstraction & Java Threads Section 2 Concurrent Programming Abstraction & Java Threads.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
ThreadThread Thread Basics Thread Synchronization Animations.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Threads Chapter 4 Reading: 4.1,4.4, Process Characteristics l Unit of resource ownership - process is allocated: n a virtual address space to.
Multithreading in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Critical Reference An occurrence of a variable v is defined to be critical reference: a. if it is assigned to in one process and has an occurrence in another.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Processes & Threads Bahareh Goodarzi. Single & Multiple Thread of control code files data code files data.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
CS333 Intro to Operating Systems Jonathan Walpole.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading in JAVA
Java Thread and Memory Model
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.
1 Computer Systems II Introduction to Processes. 2 First Two Major Computer System Evolution Steps Led to the idea of multiprogramming (multiple concurrent.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Multithreading. Multithreaded Programming A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is.
Thread basics. A computer process Every time a program is executed a process is created It is managed via a data structure that keeps all things memory.
1 OS Review Processes and Threads Chi Zhang
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
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,
Implementing Lock. From the Previous Lecture  The “too much milk” example shows that writing concurrent programs directly with load and store instructions.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
1 Introduction to Threads Race Conditions. 2 Process Address Space Revisited Code Data OS Stack (a)Process with Single Thread (b) Process with Two Threads.
Java Thread Programming
Multi Threading.
Java Multithreading.
Chapter 2 Processes and Threads Today 2.1 Processes 2.2 Threads
Threads Chate Patanothai.
Threads and Concurrency in Java: Part 1
Multithreading.
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
CS333 Intro to Operating Systems
Representation and Management of Data on the Internet
CMSC 202 Threads.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CMSC 330: Organization of Programming Languages Threads

CMSC 3302 Computation Abstractions CPU 1CPU 2 p3p1p2p4 t1 t2 t1 t2 t3 t1 t4 t5 A computer Processes (e.g., JVM’s)‏ Threads

CMSC 3303 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 process

CMSC 3304 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 processes have at least one thread (main)‏ –Programs vs. processes

CMSC 3305 Implementation View Per-thread stack and instruction pointer –Saved in memory when thread suspended –Put in hardware esp/eip when thread resumes eip esp

CMSC 3306 Tradeoffs 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 usage

CMSC 3307 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 They're part of the Java language specification

CMSC 3308 Java Threads Every application has at least one thread –The “main” thread, started by the JVM to run the application’s main() method 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.

CMSC 3309 Thread Creation execution (time)‏ main thread thread starts thread ends thread join

CMSC Thread 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() method concurrently with the current thread –Thread terminates when its run() method returns

CMSC Running Example: Alarms Goal: To set alarms which will be triggered in the future –Input: time t (seconds) and message m –Result: we’ll see m printed after t seconds

CMSC 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); } like phone calls thrown when another thread calls interrupt

CMSC 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); }

CMSC 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(); }

CMSC 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)‏

CMSC 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); }

CMSC 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(); }

CMSC Notes: Passing Parameters run() doesn’t take parameters We “pass parameters” to the new thread by storing them as private fields in the class that extends Runnable –Example: the time to wait and the message to print in the AlarmThread class

CMSC Concurrency A concurrent program is one that has multiple threads 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 more common –Multi-CPU machines aren't that expensive any more –Dual-core CPUs are available now

CMSC Scheduling Example (1)‏ CPU 1 CPU 2 p1 p2 p1 p2 One process per CPU p2 threads: p1 threads:

CMSC Scheduling Example (2)‏ CPU 1 CPU 2 p1 p2 p1 p2 Threads shared between CPUs p2 threads: p1 threads:

CMSC Concurrency 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 with each other Communication is done by sharing data –In Java, different threads may access the heap simultaneously –But the scheduler might interleave threads arbitrarily –Problems can occur if we’re not careful.

CMSC Data Race Example public 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 Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 Start: both threads ready to run. Each will increment the global cnt. Shared state

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 T1 executes, grabbing the global counter value into its own y. Shared state y = 0

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T1 executes again, storing its value of y + 1 into the counter. Shared state y = 0

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T1 finishes. T2 executes, grabbing the global counter value into its own y. Shared state y = 0 y = 1

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 2 T2 executes, storing its incremented cnt value into the global counter. Shared state y = 0 y = 1

CMSC But When it's Run Again?

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 Start: both threads ready to run. Each will increment the global count. Shared state

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 T1 executes, grabbing the global counter value into its own y. Shared state y = 0

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 0 T1 is preempted. T2 executes, grabbing the global counter value into its own y. Shared state y = 0

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T2 executes, storing the incremented cnt value. Shared state y = 0

CMSC Data Race Example static int cnt = 0; t1.run() { int y = cnt; cnt = y + 1; } t2.run() { int y = cnt; cnt = y + 1; } cnt = 1 T2 completes. T1 executes again, storing the incremented original counter value (1) rather than what the incremented updated value would have been (2)! Shared state y = 0

CMSC What Happened? Different schedules led to different outcomes –This is a data race or race condition A thread was preempted in the middle of an operation –Reading and writing cnt was supposed to be atomic- to happen with no interference from other threads –But the schedule (interleaving of threads) which was chosen allowed atomicity to be violated –These bugs can be extremely hard to reproduce, and so hard to debug Depends on what scheduler chose to do, which is hard to predict

CMSC Question If instead of int y = cnt; cnt = y+1; We had written –cnt++; Would the result be any different? Answer: NO! –Don’t depend on your intuition about atomicity

CMSC Question If you run a program with a race condition, will you always get an unexpected result? –No! It depends on the scheduler, i.e., which JVM you’re running, and on the other threads/processes/etc, that are running on the same CPU Race conditions are hard to find

CMSC What’s Wrong with the Following? Threads may be interrupted after the while but before the assignment x = 1 –Both may think they “hold” the lock! This is busy waiting –Consumes lots of processor cycles Thread 1 while (x != 0); x = 1; cnt++; x = 0; Thread 2 while (x != 0); x = 1; cnt++; x = 0; static int cnt = 0; static int x = 0;

CMSC Aside: Functional Programming No side effects No memory access No data races! Easier to parallelize functional programs

CMSC Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent program. Different languages have adopted different mechanisms to allow the programmer to synchronize threads. Java has several mechanisms; we'll look at locks first.

CMSC Locks (Java 1.5)‏ Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until the lock becomes available Reentrant lock can be reacquired by same thread –As many times as desired –No other thread may acquire a lock until has been released same number of times it has been acquired interface Lock { void lock(); void unlock();... /* Some more stuff, also */ } class ReentrantLock implements Lock {... }

CMSC Avoiding Interference: Synchronization public class Example extends Thread { private static int cnt = 0; static Lock foo = new ReentrantLock(); public void run() { foo.lock(); int y = cnt; cnt = y + 1; foo.unlock(); } … } Lock, for protecting the shared state Acquires the lock; Only succeeds if not held by another thread Releases the lock

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 0Shared state T1 acquires the lock

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 0Shared state T1 reads cnt into y y = 0

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 0Shared state T1 is preempted. T2 attempts to acquire the lock but fails because it’s held by T1, so it blocks y = 0

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 1Shared state T1 runs, assigning to cnt y = 0

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 1Shared state T1 releases the lock and terminates y = 0

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 1Shared state T2 now can acquire the lock. y = 0

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 1Shared state T2 reads cnt into y. y = 0 y = 1

CMSC Applying Synchronization int cnt = 0; t1.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } t2.run() { lock.lock(); int y = cnt; cnt = y + 1; lock.unlock(); } cnt = 2Shared state T2 assigns cnt, then releases the lock y = 0 y = 1

CMSC Different Locks Don’t Interact This program has a race condition –Threads only block if they try to acquire a lock held by another thread static int cnt = 0; static Lock l = new ReentrantLock(); static Lock m = new ReentrantLock(); void inc() { l.lock(); cnt++; l.unlock(); } void inc() { m.lock(); cnt++; m.unlock(); }

CMSC Reentrant Lock Example Reentrancy is useful because each method can acquire/release locks as necessary –No need to worry about whether callers have locks –Discourages complicated coding practices static int cnt = 0; static Lock l = new ReentrantLock(); void inc() { l.lock(); cnt++; l.unlock(); } void returnAndInc() { int temp; l.lock(); temp = cnt; inc(); l.unlock(); }