Threads & Concurrency

Similar documents
Threads & Concurrency

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

Threads, Concurrency, and Parallelism

THREADS & CONCURRENCY

THREADS & CONCURRENCY

THREADS AND CONCURRENCY

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 AND SYNCHRONIZATION

What is a thread anyway?

Synchronized Methods of Old Versions of Java

Reintroduction to Concurrency

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

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

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

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

Object Oriented Programming. Week 10 Part 1 Threads

Threads Questions Important Questions

CMSC 330: Organization of Programming Languages

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

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

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Advanced Programming Methods. Lecture 6 - Concurrency in Java (1)

CS193k, Stanford Handout #8. Threads 3

Threads Chate Patanothai

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

Concurrent Programming using Threads

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

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

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

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

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

Introduction to Java Threads

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

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Parallel Programming Languages COMP360

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

Module - 4 Multi-Threaded Programming

Race Conditions & Synchronization

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

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

CS 351 Design of Large Programs Threads and Concurrency

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Only one thread can own a specific monitor

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

Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

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

Parallelism Marco Serafini

Concurrent Programming Benoît Garbinato

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

Chapter 32 Multithreading and Parallel Programming

Animation Part 2: MoveableShape interface & Multithreading

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

Consistency: Strict & Sequential. SWE 622, Spring 2017 Distributed Software Engineering

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

Dealing with Issues for Interprocess Communication

The deadlock problem

Multi-threading in Java. Jeff HUANG

CS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University

CSCD 330 Network Programming

Lesson 6: Process Synchronization

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Introduction to Parallel Computing

Problems with Concurrency. February 19, 2014

Deadlock CS 241. March 19, University of Illinois

CSCD 330 Network Programming

Java Threads. Introduction to Java Threads

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

7. MULTITHREDED PROGRAMMING

EECS 482 Introduction to Operating Systems

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

CPS221 Lecture: Threads

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

Concurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter

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

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

Software Practice 1 - Multithreading

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

G52CON: Concepts of Concurrency

CS11 Java. Fall Lecture 7

About this exam review

Concurrent Programming

CS162 Operating Systems and Systems Programming Lecture 11 Page Allocation and Replacement"

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

PROVING THINGS ABOUT PROGRAMS

Unit - IV Multi-Threading

CS 241 Honors Concurrent Data Structures

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

Programming in Parallel COMP755

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

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

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

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Introduction to Concurrency (Processes, Threads, Interrupts, etc.)

Race Conditions & Synchronization

Performance Throughput Utilization of system resources

Transcription:

Threads & Concurrency Lecture 24 CS2110 Spring 2017

Due date of A7 Due d About A5-A6 2 We have changed the due date of A7 Friday, 28 April. But the last date to submit A7 remains the same: 29 April. We make the last date be 29 April so that people who are working on A8 can use our solution to A7 beginning on 30 April We will get caught up on grading A6 and regrading A5 and A6.

Today: New topic: concurrency 3 Modern computers have multiple cores Instead of a single CPU (central processing unit) on the chip 5-10 common. Intel has prototypes with 80! 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

Why multicore? 4 Moore s Law: Computer speeds and memory densities nearly double each year

Magnetic-core memory. A penny a bit 5 What memory was like, 1955..1975. At 1 penny per bit, a gigabyte would cost $80,000, 000 From Wikipedia upload.wikimedia.org/ wikipedia/commons/d/da/ KL_CoreMemory.jpg

Magnetic-core memory. A penny a bit 6 Each ring is either magnetized or unmagnetized (1 or 0). To set (Y4, X3) send impulse down wires Y4 and X3. Enough voltage to change that one but not others. Sense wire goes through all cores and detects whether something changed.

But a fast computer runs hot 7 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!

Programming a Cluster... 8 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)

9 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

Part of Activity Monitor in Gries s laptop 10 >100 processes are competing for time. Here s some of them:

Concurrency 11 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

Race conditions 12 A race condition arises if two or more processes access the same variables or objects concurrently and at least one does updates Example: 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 13 Suppose x is initially 5 Thread t1 LOAD x ADD 1 STORE x Thread t2... LOAD x ADD 1 STORE x... after finishing, x = 6! We lost an update

Race conditions 14 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!

Deadlock 15 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. Examples of resources are: A file to be read An object that maintains a stack, a linked list, a hash table, etc. 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.

16 Dining philosopher problem Five philosophers sitting at a table. Each repeatedly does this: 1. think 2. eat What do they eat? spaghetti. Need TWO forks to eat spaghetti!

17 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 DEADLOCK!

18 Dining philosopher problem 5 4 1 3 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 2

Java: What is a Thread? 19 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

Thread 20 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

Java class Thread 21 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)

Creating a new Thread (Method 1) 22 class PrimeThread extends Thread { long a, b; overrides Thread.run() PrimeThread(long a, long b) { this.a= a; this.b= b; @Override public void run() { //compute primes between a and b... Call run() directly? no new thread is used: Calling p.start() will run it PrimeThread p= new PrimeThread(143, 195); p.start(); Do this and Java invokes run() in new thread

23 Creating a new method Thread run() (Method 1) executes in one thread while class PTd extends Thread main { program long a, b; coninues to PTd (long a, long b) { execute this.a= a; this.b= b; @Override public void run() { //compute primes between a, b... Calls start() in PTd p= new PTd (143, 195); p.start(); Thread partition continue doing other stuff PTd@20 start() run() sleep(long) interrupt isinterrupted yield isalive a b run() Calls run() to execute in a new Thread Thread and then returns getid() getname getpriority PTd

Creating a new Thread (Method 2) 24 class PrimeRun implements Runnable { long a, b; PrimeRun(long a, long b) { this.a= a; this.b= b; public void run() { //compute primes between a and b... PrimeRun p= new PrimeRun(143, 195); new Thread(p).start();

Example 25 public class ThreadTest extends Thread { int M= 1000; int R= 600; public static void main(string[] args) { new ThreadTest().start(); for (int h= 0; true; h= h+1) { sleep(m); We ll demo this with different values of M and R. Code will be on course website System.out.format("%s %d\n", Thread.currentThread(), h); sleep( ) requires @Override public void run() { a throws clause for (int k= 0; true; k= k+1) { or else catch it sleep(r); System.out.format("%s %d\n", Thread.currentThread(), k);

Example Thread name, priority, thread group 26 public class ThreadTest extends Thread { int M= 1000; int R= 600; public static void main(string[] args) { new ThreadTest().start(); for (int h= 0; true; h= h+1) { sleep(m); @Override public void run() { for (int k= 0; true; k= k+1) { sleep(r); format("%s %d\n", Thread.currentThread(), k); Thread[Thread-0,5,main] 0 Thread[main,5,main] 0 Thread[Thread-0,5,main] 1 Thread[Thread-0,5,main] 2 Thread[main,5,main] 1 format("%s %d\n", Thread.currentThread(), Thread[Thread-0,5,main] h); 3 Thread[main,5,main] 2 Thread[Thread-0,5,main] 4 Thread[Thread-0,5,main] 5 Thread[main,5,main] 3

27 Example public class ThreadTest extends Thread { static boolean ok = true; public static void main(string[] args) { new ThreadTest().start(); for (int i = 0; i < 10; i++) { System.out.println("waiting..."); yield(); ok = false; public void run() { while (ok) { System.out.println("running..."); yield(); System.out.println("done"); waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... waiting... running... done If threads happen to be sharing a CPU, yield allows other waiting threads to run.

Terminating Threads is tricky 28 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.

Background (daemon) Threads 29 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.) A daemon can continue even when the thread that created it stops. On your computer, the same notion of background workers explains why so many things are always running in the task manager.

Background (daemon) Threads 30 demon: an evil spirit daemon. Fernando Corbato, 1963, first to use term. Inspired by Maxwell s daemon, an imaginary agent in physics and thermodynamics that helped to sort molecules. from the Greek δαίμων. Unix System Administration Handbook, page 403: Daemons have no particular bias toward good or evil but rather serve to help define a person's character or personality. The ancient Greeks' concept of a "personal daemon" was similar to the modern concept of a "guardian angel" eudaemonia is the state of being helped or protected by a kindly spirit. As a rule, UNIX systems seem to be infested with both daemons and demons.

31 Beginning to think about avoiding race conditions You know that race conditions can create problems: Basic idea of race condition: Two different threads access the same variable in a way that destroys correctness. Process t1 Process t2... x= x + 1; x= x + 1; But x= x+1; is not an atomic action : it takes several step Two threads may want to use the same stack, or Hash table, or linked list, or at the same time.

Synchronization 32 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

Solution: use with synchronization 33 private Stack<String> stack= new Stack<String>(); public void dosomething() { synchronized (stack) { if (stack.isempty()) return; String s= stack.pop(); //do something with s... synchronized block Put critical operations in a synchronized block Can t be interrupted by other synchronized blocks on the same object Can run concurrently with non-synchronized code Or code synchronized on a different object!

Synchronization 34 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

Example: a lucky scenario 35 private Stack<String> stack= new Stack<String>(); public void dosomething() { 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 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