THREADS & CONCURRENCY

Similar documents
THREADS & CONCURRENCY

THREADS AND CONCURRENCY

Threads & Concurrency

Threads & Concurrency

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Threads, Concurrency, and Parallelism

What is a Thread? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking)

A6 AND A START ON THREADS AND CONCURRENCY

Race Conditions & Synchronization

RACE CONDITIONS AND SYNCHRONIZATION

Synchronization Lecture 24 Fall 2018

Results of prelim 2 on Piazza

Race Conditions & Synchronization

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21

What is a thread anyway?

Reintroduction to Concurrency

Synchronization Lecture 23 Fall 2017

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

CMSC 132: Object-Oriented Programming II. Threads in Java

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Threads Questions Important Questions

CS 351 Design of Large Programs Threads and Concurrency

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Synchronized Methods of Old Versions of Java

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Threads Chate Patanothai

Introduction to Java Threads

Java Threads. Introduction to Java Threads

Concurrent Programming

CMSC 330: Organization of Programming Languages

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

Lecture 27: Safety and Liveness Properties, Java Synchronizers, Dining Philosophers Problem

Lesson 6: Process Synchronization

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Concurrency, Mutual Exclusion and Synchronization C H A P T E R 5

Dealing with Issues for Interprocess Communication

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

CS193k, Stanford Handout #8. Threads 3

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Chapter 32 Multithreading and Parallel Programming

CS 159: Parallel Processing

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Parallel Programming Languages COMP360

Concurrent Programming Benoît Garbinato

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition

Java Threads. COMP 585 Noteset #2 1

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004

Java s Implementation of Concurrency, and how to use it in our applications.

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Concurrency in Java Prof. Stephen A. Edwards

CS11 Java. Fall Lecture 7

CSE 4/521 Introduction to Operating Systems

CS 351 Design of Large Programs Introduction to Multi-Threaded Programming in Java

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Advances in Programming Languages

Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

Object Oriented Programming and Design in Java. Session 18 Instructor: Bert Huang

Introduction to Concurrent Software Systems. CSCI 5828: Foundations of Software Engineering Lecture 08 09/17/2015

SFDV3006 Concurrent Programming

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

Concurrent Computing CSCI 201 Principles of Software Development

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

Performance Throughput Utilization of system resources

Parallelism Marco Serafini

Concurrent Programming using Threads

Only one thread can own a specific monitor

! Why is synchronization needed? ! Synchronization Language/Definitions: ! How are locks implemented? Maria Hybinette, UGA

Chapter 6: Process [& Thread] Synchronization. CSCI [4 6] 730 Operating Systems. Why does cooperation require synchronization?

Introduction to Concurrent Software Systems. CSCI 5828: Foundations of Software Engineering Lecture 12 09/29/2016

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

Dining Philosophers, Semaphores

CS370 Operating Systems

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Threads and Too Much Milk! CS439: Principles of Computer Systems February 6, 2019

CS370 Operating Systems

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Threads and Parallelism in Java

Deadlock CS 241. March 19, University of Illinois

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Lecture Topics. Announcements. Today: Concurrency (Stallings, chapter , 5.7) Next: Exam #1. Self-Study Exercise #5. Project #3 (due 9/28)

Chapter 4: Threads. Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads

User Space Multithreading. Computer Science, University of Warwick

Computer Systems II. First Two Major Computer System Evolution Steps

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

Animation Part 2: MoveableShape interface & Multithreading

CS 475. Process = Address space + one thread of control Concurrent program = multiple threads of control

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Processes The Process Model. Chapter 2. Processes and Threads. Process Termination. Process Creation

Transcription:

4/26/16 Announcements BRING YOUR CORNELL ID TO THE PRELIM. 2 You need it to get in THREADS & CONCURRENCY Prelim 2 is next Tonight BRING YOUR CORNELL ID! A7 is due Thursday. Our Heap.java: on Piazza (A7 FAQs) A8. Firm deadline, no late ones permitted. We have to get it graded and get letter grades calculated immediately so you can determine whether to take the final. Final: 17 May For A8. Get the simplest solution correct on both parts before attempting to improve! Cheating cases found and we are processing them. Please don t cheat! Two versions of dfs (different specs) on Piazza Supplementary material note Lecture 23 CS2110 Spring 2016 Today: New topic: concurrency 3 Why multicore? 4 Modern computers have multiple cores Instead of a single CPU (central processing unit) on the chip 5-10 common. Intel has prototypes with 80! Moore s Law: Computer speeds and memory densities nearly double each year We often run many programs at the same time Even with a single core, your program may have more than one thing to do at a time Argues for having a way to do many things at once But a fast computer runs hot 5 Programming a Cluster 6 Power dissipation rises as square of the clock rate Chips were heading toward melting down! Multicore: with four CPUs (cores) on one chip, even if we run each at half speed we can perform more overall computations! Sometimes you want to write a program that is executed on many machines! Atlas Cluster (at Cornell): 768 cores 1536 GB RAM 24 TB Storage 96 NICs (Network Interface Controller) 1

7 Many processes are executed simultaneously on your computer Operating system provides support for multiple processes Usually fewer processors than processes Processes are an abstraction: at hardware level, lots of multitasking memory subsystem video controller buses instruction prefetching 8 Part of Activity Monitor in Gries s laptop >100 processes are competing for time. Here s some of them: Concurrency Race conditions 9 10 Concurrency refers to a single program in which several processes, called threads, are running simultaneously Special problems arise They see the same data and hence can interfere with each other, e.g. one process modifies a complex structure like a heap while another is trying to read it CS2110: we focus on two main issues: Race conditions Deadlock A race condition arises if two or more processes access the same variables or objects concurrently and at least one does updates : Processes t1 and t2 x= x + 1; for some static global x. Process t1 Process t2 x= x + 1; x= x + 1; But x= x+1; is not an atomic action : it takes several steps Race conditions Race conditions 11 12 Suppose x is initially 5 Thread t1 LOAD x ADD 1 STORE x Thread t2 LOAD x ADD 1 STORE x Typical race condition: two processes wanting to change a stack at the same time. Or make conflicting changes to a database at the same time. Race conditions are bad news Race conditions can cause many kinds of bugs, not just the example we see here! Common cause for blue screens : null pointer exceptions, damaged data structures Concurrency makes proving programs correct much harder! after finishing, x = 6! We lost an update 2

13 Deadlock 14 Dining philosopher problem Five philosophers sitting at a table. To prevent race conditions, one often requires a process to acquire resources before accessing them, and only one process can acquire a given resource at a time. s of resources are: A file to be read An object that maintains a stack, a linked list, a hash table, etc. Each repeatedly does this: 1. think 2. eat What do they eat? spaghetti. But if processes have to acquire two or more resources at the same time in order to do their work, deadlock can occur. This is the subject of the next slides. Need TWO forks to eat spaghetti! 15 Dining philosopher problem Each does repeatedly : 1. think 2. eat (2 forks) eat is then: pick up left fork pick up right fork pick up food, eat put down left fork put down rght fork At one point, they all pick up their left forks 16 Dining philosopher problem 5 4 3 1 2 Simple solution to deadlock: Number the forks. Pick up smaller one first 1. think 2. eat (2 forks) eat is then: pick up smaller fork pick up bigger fork pick up food, eat put down bigger fork put down smallerfork DEADLOCK! Java: What is a Thread? Thread 17 18 A separate execution that runs within a single program and can perform a computational task independently and concurrently with other threads Many applications do their work in just a single thread: the one that called main() at startup But there may still be extra threads Garbage collection runs in a background thread GUIs have a separate thread that listens for events and dispatches calls to methods to process them Today: learn to create new threads of our own in Java A thread is an object that independently computes Needs to be created, like any object Then started --causes some method to be called. It runs side by side with other threads in the same program; they see the same global data The actual executions could occur on different CPU cores, but but don t have to We can also simulate threads by multiplexing a smaller number of cores over a larger number of threads 3

Java class Thread Creating a new Thread (Method 1) 19 threads are instances of class Thread Can create many, but they do consume space & time The Java Virtual Machine creates the thread that executes your main method. Threads have a priority Higher priority threads are executed preferentially By default, newly created threads have initial priority equal to the thread that created it (but priority can be changed) 20 overrides class PrimeThread extends Thread { long a, b; PrimeThread(long a, long b) { this.a= a; this.b= b; Thread.run() @Override //compute primes between a and b Call run() directly? no new thread is used: Calling thread will run it PrimeThread p= new PrimeThread(143, 195); p.start(); Do this and Java invokes run() in new thread 21 Creating a new Thread (Method 2) class PrimeRun implements Runnable { long a, b; PrimeRun(long a, long b) { this.a= a; this.b= b; //compute primes between a and b PrimeRun p= new PrimeRun(143, 195); new Thread(p).start(); 22 public class ThreadTest extends Thread { public static void main(string[] args) { Thread name, priority, thread group Thread[Thread-0,5,main] 0 Thread[main,5,main] 0 Thread[main,5,main] 1 Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 Thread[Thread-0,5,main] 1 Thread[Thread-0,5,main] 2 Thread[Thread-0,5,main] 3 Thread[Thread-0,5,main] 4 Thread[Thread-0,5,main] 5 Thread[Thread-0,5,main] 6 Thread[Thread-0,5,main] 7 Thread[Thread-0,5,main] 8 Thread[Thread-0,5,main] 9 23 Thread[main,5,main] 0 Thread[main,5,main] 1 public class ThreadTest extends Thread { public static void main(string[] args) { currentthread().setpriority(4); Thread name, priority, thread group Thread[main,5,main] 2 Thread[main,5,main] 3 Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 Thread[Thread-0,4,main] 0 Thread[Thread-0,4,main] 1 Thread[Thread-0,4,main] 2 Thread[Thread-0,4,main] 3 Thread[Thread-0,4,main] 4 Thread[Thread-0,4,main] 5 Thread[Thread-0,4,main] 6 Thread[Thread-0,4,main] 7 Thread[Thread-0,4,main] 8 Thread[Thread-0,4,main] 9 Thread name, priority, thread group 24 Thread[main,5,main] 0 Thread[main,5,main] 1 public class ThreadTest extends Thread { Thread[main,5,main] 2 Thread[main,5,main] 3 public static void main(string[] args) { Thread[main,5,main] 4 Thread[main,5,main] 5 Thread[Thread-0,6,main] 0 Thread[Thread-0,6,main] 1 Thread[Thread-0,6,main] 2 Thread[Thread-0,6,main] 3 Thread[Thread-0,6,main] 4 Thread[Thread-0,6,main] 5 Thread[Thread-0,6,main] 6 currentthread().setpriority(6); Thread[Thread-0,6,main] 7 Thread[Thread-0,6,main] 8 Thread[Thread-0,6,main] 9 Thread[main,5,main] 6 Thread[main,5,main] 7 Thread[main,5,main] 8 Thread[main,5,main] 9 4

25 public class ThreadTest extends Thread { static boolean ok = true; If threads happen to be sharing a CPU, yield allows other waiting threads to run. done public static void main(string[] args) { for (int i = 0; i < 10; i++) { System.out.println(""); yield(); ok = false; while (ok) { System.out.println(""); yield(); System.out.println("done"); 26 Terminating Threads is tricky Easily done but only in certain ways Safe way to terminate a thread: return from method run Thread throws uncaught exception? whole program will be halted (but it can take a second or two ) Some old APIs have issues: stop(), interrupt(), suspend(), destroy(), etc. Issue: Can easily leave application in a broken internal state. Many applications have some kind of variable telling the thread to stop itself. Threads can pause Background (daemon) Threads 27 28 When active, a thread is runnable. It may not actually be running. For that, a CPU must schedule it. Higher priority threads could run first. A thread can pause Call Thread.sleep(k) to sleep for k milliseconds Doing I/O (e.g. read file, wait for mouse input, open file) can cause thread to pause Java has a form of locks associated with objects. When threads lock an object, one succeeds at a time. In many applications we have a notion of foreground and background (daemon) threads Foreground threads are doing visible work, like interacting with the user or updating the display Background threads do things like maintaining data structures (rebalancing trees, garbage collection, etc.) On your computer, the same notion of background workers explains why so many things are always running in the task manager. : a lucky scenario : an unlucky scenario 29 private Stack<String> stack= new Stack<String>(); 30 private Stack<String> stack = new Stack<String>(); if (stack.isempty()) return; String s= stack.pop(); //do something with s if (stack.isempty()) return; String s= stack.pop(); //do something with s Suppose threads A and B want to call dosomething(), and there is one element on the stack Suppose threads A and B want to call dosomething(), and there is one element on the stack 1. thread A tests stack.isempty() false 2. thread A pops stack is now empty 3. thread B tests stack.isempty() true 4. thread B just returns nothing to do 1. thread A tests stack.isempty() false 2. thread B tests stack.isempty() false 3. thread A pops stack is now empty 4. thread B pops Exception! 5

Synchronization Solution: use with synchronization 31 Java has one primary tool for preventing race conditions. you must use it by carefully and explicitly it isn t automatic. Called a synchronization barrier Think of it as a kind of lock n Even if several threads try to acquire the lock at once, only one can succeed at a time, while others wait n When it releases the lock, another thread can acquire it n Can t predict the order in which contending threads get the lock but it should be fair if priorities are the same 32 private Stack<String> stack = new Stack<String>(); synchronized (stack) { if (stack.isempty()) return; String s= stack.pop(); //do something with s synchronized block Put critical operations in a synchronized block The stack object acts as a lock Only one thread can own the lock at a time Solution: locking Synchronization + priorities 33 34 You can lock on any object, including this synchronized (this) { Syntactic sugar for the above: public synchronized void dosomething() { Combining mundane features can get you in trouble Java has priorities and synchronization But they don t mix nicely High-priority runs before low priority The lower priority thread starves Even worse With many threads, you could have a second high priority thread stuck waiting on that starving low priority thread! Now both are starving Fancier forms of locking Finer grained synchronization 35 36 Java developers have created various synchronization abstract data types Semaphores: a kind of synchronized counter (invented by Dijkstra) Event-driven synchronization Java allows you to do fancier synchronization But can only be used inside a synchronization block Special primatives called wait/notify The Windows and Linux and Apple O/S have kernel locking features, like file locking But for Java, synchronized is the core mechanism 6

37 wait/notify Suppose we put this inside an object called animator: boolean isrunning = true; public synchronized void run() { while (true) { while (isrunning) { //do one step of simulation try { wait(); catch (InterruptedException ie) { isrunning = true; notifies processes waiting for animator lock must be synchronized! relinquishes lock on animator awaits notification public void stopanimation() { animator.isrunning = false; public void restartanimation() { synchronized(animator) { animator.notify(); 38 Summary Use of multiple processes and multiple threads within each process can exploit concurrency n Which may be real (multicore) or virtual (an illusion) When using threads, beware! n Synchronize any shared memory to avoid race conditions n Synchronize objects in certain order to avoid deadlocks n Even with proper synchronization, concurrent programs can have other problems such as livelock Serious treatment of concurrency is a complex topic (covered in more detail in cs3410 and cs4410) 7