Threads, Concurrency, and Parallelism

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

Threads & Concurrency

Threads & Concurrency

THREADS AND CONCURRENCY

THREADS & CONCURRENCY

THREADS & 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

What is a thread anyway?

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

RACE CONDITIONS AND SYNCHRONIZATION

Reintroduction to Concurrency

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

Synchronization Lecture 23 Fall 2017

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

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

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

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

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

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

Synchronized Methods of Old Versions of Java

Threads Chate Patanothai

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

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

Concurrent Programming using Threads

CMSC 330: Organization of Programming Languages

CS193k, Stanford Handout #8. Threads 3

Multi-threading in Java. Jeff HUANG

Threads Questions Important Questions

Concurrent Programming Benoît Garbinato

Synchronization Lecture 24 Fall 2018

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

Dealing with Issues for Interprocess Communication

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

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

Chapter 32 Multithreading and Parallel Programming

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

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

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

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

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

Introduction to Java Threads

The New Java Technology Memory Model

Problems with Concurrency. February 19, 2014

CS 351 Design of Large Programs Threads and Concurrency

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

CMSC 330: Organization of Programming Languages

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

Object Oriented Programming. Week 10 Part 1 Threads

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

Process Synchronization

Synchronization Principles

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

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

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

Synchronization in Java

Programming in Parallel COMP755

Threads and Parallelism in Java

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

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Lesson 6: Process Synchronization

Concurrent Programming. Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

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

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

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

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

Introduction to OS Synchronization MOS 2.3

Animation Part 2: MoveableShape interface & Multithreading

Threads and Java Memory Model

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

Chapter 2 Processes and Threads

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

Principles of Software Construction: Concurrency, Part 2

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall

Only one thread can own a specific monitor

G52CON: Concepts of Concurrency

CS11 Java. Fall Lecture 7

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Unit - IV Multi-Threading

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

Parallel Programming Languages COMP360

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

Game Engineering: 2D

Race Conditions & Synchronization

PROCESS SYNCHRONIZATION

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Multiple Inheritance. Computer object can be viewed as

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

The deadlock problem

Concurrency in Java Prof. Stephen A. Edwards

Processes The Process Model. Chapter 2 Processes and Threads. Process Termination. Process States (1) Process Hierarchies

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

Concept of a process

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

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

CS370 Operating Systems

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

Transcription:

Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017

Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start writing programs that do more than one thing at at a time.

Concurrent Work

Concurrency in Multiple Machines Datacenters and clusters are everywhere: Industrial: Google, Microsoft, Amazon, Apple, Facebook Scientific: Several big clusters just in Gates Hall.

Multicore Processors Every desktop, laptop, tablet, and smartphone you can buy has multiple processors.

Concurrency & Parallelism Parallelism is about using additional computational resources to produce an answer faster. Concurrency is about controlling access by multiple threads to shared resources. A thread or thread of execution is a sequential stream of computational work.

Java: What is a Thread? 8 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 9 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 10 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)

Threads in Java public static void main() {... Main Thread CPU

Threads in Java public static void main() {... void run() {... Main Thread void run() {... CPU

Threads in Java public static void main() {... void run() {... Main Thread void run() {... CPU

Starting a new Java thread 1. Make a new class that implements Runnable. 2. Put your code for the thread in the run() method. Don t call the run method directly! 3. Construct a new Thread with the Runnable: SomeRunnable r = new SomeRunnable(...); Thread t = new Thread(r); 4. Call the Thread s start() method.

Sequential version: starting prime composite done! main check1 main check2 main time

Parallel version: starting done! main prime check1 check2 composite time

Creating a new Thread (Method 1) 17 class PrimeThread extends Thread { long a, b; PrimeThread(long a, long b) { this.a= a; this.b= b; overrides Thread.run() @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

Creating a new method Thread run() (Method 1) executes in one 18 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... PTd p= new PTd (143, Calls 195); start() in 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) 19 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 20 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 a throws clause or else catch it @Override public void run() { for (int k= 0; true; k= k+1) { sleep(r); System.out.format("%s %d\n", Thread.currentThread(), k);

Example Thread name, priority, thread group 21 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); format("%s %d\n", Thread.currentThread(), h); @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 Thread[Thread-0,5,main] 3 Thread[main,5,main] 2 Thread[Thread-0,5,main] 4 Thread[Thread-0,5,main] 5 Thread[main,5,main] 3

22 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 - The safe way: return from the run() method. - Use a flag field to tell the thread when to exit. - Avoid old and dangerous APIs: stop(), interrupt(), suspend(), destroy() - These can leave the thread in a broken state.

Background (daemon) Threads 24 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 25 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.

Producer & Consumer generate a prime; queue.add(p); q = queue.remove(); System.out.println(q); queue producer consumer

Producer & Consumers generate a prime; queue.add(p); producer queue q = queue.remove(); System.out.println(q); q = queue.remove(); System.out.println(q); q = queue.remove(); System.out.println(q); consumers

Timing is Everything Thread 1 Thread 2 if (!q.isempty()) { long p = q.remove(); if (!q.isempty()) { long p = q.remove();

A Fortunate Interleaving Thread 1 Thread 2 queue length: 1 if (!q.isempty()) { long p = q.remove(); Condition is true! Remove an element. queue length: 0 Condition is false. Do nothing. if (!q.isempty()) { long p = q.remove(); time queue length: 0

Another Fortunate Interleaving Thread 1 Thread 2 queue length: 1 if (!q.isempty()) { long p = q.remove(); queue length: 0 if (!q.isempty()) { long p = q.remove(); time queue length: 0

An Unfortunate Interleaving Thread 1 Thread 2 queue length: 1 Condition is true. if (!q.isempty()) { queue length: 1 if (!q.isempty()) { Condition is still true. queue length: 1 Remove an element. long p = q.remove(); queue length: 0 long p = q.remove(); NoSuchElementException! time

32 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 But x= x+1; is not an... atomic action : it x= x + 1; x= x + 1; takes several step Two threads may want to use the same stack, or Hash table, or linked list, or at the same time.

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

Synchronized Blocks a.k.a. locks or mutual exclusion synchronized (obj) {... At most one thread can be in a synchronized (obj) block for the same obj at any given time.

Synchronized Blocks a.k.a. locks or mutual exclusion synchronized (q) { if (!q.isempty()) { q.remove(); At most one consumer thread can be trying to remove something from the queue at a time.

Solution: use with synchronization 36 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!

Example: a lucky scenario 37 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

What Can i Be at the End? Thread 1 Thread 2 Initially, i = 0 i += 1; i += 1; Finally, i =?

What Can i Be at the End? Thread 1 Thread 2 Initially, i = 0 i += 1; i += 1; Finally, i = 2 or 1!

What Can i Be at the End? Thread 1 Thread 2 Initially, i = 0 tmp = load i; tmp = tmp + 1; store tmp to i; tmp = load i; tmp = tmp + 1; store tmp to i;

What Can i Be at the End? Thread 1 Thread 2 Initially, i = 0 tmp = load i; Load 0 from memory Load 0 from memory tmp = load i; tmp = tmp + 1; store tmp to i; Store 1 to memory time Store 1 to memory Finally, i = 1 tmp = tmp + 1; store tmp to i;

A Pretty Good Rule Whenever you read or write variables that multiple threads might access, always wrap the code in a synchronized block. (Following this rule will not magically make your code correct, and it is not always strictly necessary to write correct code. But it is usually a good idea.)

Race Conditions When the result of running two (or more) threads depends on the relative timing of the executions. - Can cause extremely subtle bugs! - Bugs that seem to disappear when you look for them!

Race conditions 44 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 Use synchronized blocks to avoid race conditions. But locks are shared resources that can create their own problems. Like other resources: files, network sockets, etc. If thread A holds a resource that thread B needs to continue, and thread B holds a different resource that thread A needs to continue, you have deadlock.

Dining philosopher problem 46 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!

Dining philosopher problem 46 Each does repeatedly : 1. think 2. eat (2 forks) eat is then: pick up left fork pick up right fork eat spaghetti put down left fork put down right fork At one point, they all pick up their left forks DEADLOCK!

Dining philosopher problem 46 48 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 eat spaghetti put down bigger fork put down smaller fork