A6 AND A START ON THREADS AND CONCURRENCY

Similar documents
THREADS & CONCURRENCY

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)

What is a thread anyway?

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

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

Race Conditions & Synchronization

Lecture #7: Implementing Mutual Exclusion

Synchronization Lecture 24 Fall 2018

Synchronization Lecture 23 Fall 2017

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

CmpSci 187: Programming with Data Structures Spring 2015

Results of prelim 2 on Piazza

Updates. Office B116E Office Hours : Friday 1 p.m. 2 p.m. Also by appointment Office Hours Purpose:

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

Concurrent Computing CSCI 201 Principles of Software Development

RACE CONDITIONS AND SYNCHRONIZATION

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

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

CS 2110 Assignment 8: Planet X

RECURSION (CONTINUED)

Reintroduction to Concurrency

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

CS 351 Design of Large Programs Threads and Concurrency

CSC369 Lecture 5. Larry Zhang, October 19,2015

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

Total Score /15 /20 /30 /10 /5 /20 Grader

Locking: A necessary evil? Lecture 10: Avoiding Locks. Priority Inversion. Deadlock

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

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Threads and Parallelism in Java

Lecture 10: Avoiding Locks

COMP110 Jump Around. Go ahead and get today s code in Eclipse as shown on next few slides. Kris Jordan

Introduction to Java Threads

Menu. In general, what are possible advantages of one design over another? Class 27: Exam 2. Exam 2 Parenthesizing the Expression. Design A.

YESTERDAY: DISTRIBUTED COMPUTING

Lecture 22: Garbage Collection 10:00 AM, Mar 16, 2018

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS61A Lecture 29 Parallel Computing. Jom Magrotker UC Berkeley EECS August 7, 2012

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

CPS221 Lecture: Threads

Concurrent Programming Benoît Garbinato

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 25: Review and Open Problems

Unit 8: Threads. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15

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

CS11 Java. Fall Lecture 7

TA hours and labs start today. First lab is out and due next Wednesday, 1/31. Getting started lab is also out

Threads. CS 475, Spring 2018 Concurrent & Distributed Systems

CSCD 330 Network Programming

CMPSCI 187: Programming With Data Structures. Lecture #20: Concurrency and a Case Study David Mix Barrington 24 October 2012

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

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Race Conditions & Synchronization

CSCD 330 Network Programming

Grand Central Dispatch and NSOperation. CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015

Midterm I October 11 th, 2006 CS162: Operating Systems and Systems Programming

CS 220: Introduction to Parallel Computing. Introduction to CUDA. Lecture 28

Total Score /15 /20 /30 /10 /5 /20 Grader

Announcements. Course Staff. Course Staff. Lectures 10/19/11. CS/ENGRD 2110 Fall Instructor. Administrative Assistant

10/31/18. About A6, Prelim 2. Spanning Trees, greedy algorithms. Facts about trees. Undirected trees

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Spanning Trees, greedy algorithms. Lecture 20 CS2110 Fall 2018

int $0x32 // call interrupt number 50

Announcements. 1. Forms to return today after class:

Dealing with Issues for Interprocess Communication

Spanning Trees, greedy algorithms. Lecture 22 CS2110 Fall 2017

Parameters and Objects

ICOM 4015-Advanced Programming. Spring Instructor: Dr. Amir H. Chinaei. TAs: Hector Franqui, Jose Garcia, and Antonio Tapia. Reference: Big Java

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

Parallel Systems. Introduction. Principles of Parallel Programming, Calvin Lin & Lawrence Snyder, Chapters 1 & 2

Java Threads. COMP 585 Noteset #2 1

Mehran Sahami Handout #7 CS 106A September 24, 2014

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Assignment #1: /Survey and Karel the Robot Karel problems due: 1:30pm on Friday, October 7th

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

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

Concurrent Programming using Threads

COMP I/O, interrupts, exceptions April 3, 2016

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

Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

RECURSION (CONTINUED)

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

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

Midterm Exam Solutions and Grading Guidelines March 3, 1999 CS162 Operating Systems

CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing

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

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

CSCI 201L Written Exam #2. 10% of course grade

Spanning Trees 4/19/17. Prelim 2, assignments. Undirected trees

Tips from the experts: How to waste a lot of time on this assignment

Spanning Trees. Lecture 22 CS2110 Spring 2017

Threads CS1372. Lecture 13. CS1372 Threads Fall / 10

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

Multiple Inheritance. Computer object can be viewed as

Transcription:

A6 AND A START ON THREADS AND CONCURRENCY Lecture 24 CS2110 Fall 2014

Administrative matters 2 PRELIM 2 Thursday, 5:30pm, Statler Auditorium (even ids) Thursday, 7:30pm, Statler Auditorium (odd ids) Those authorized to have more time or a quieter space: 5:00PM onward, Statler 196 Recitation this week: Those in recitation 2110-208 Tu 1:25PM - 2:15PM in Olin Hall 218. Leon is out of town. Please go to room Olin 245 instead and attend Eric Perdew s recitation.

Concurrency 3 Modern computers have multiple cores Instead of a single CPU on the chip 4-8 common on laptops And even with a single core (CPU) your program may have more than one thing to do at a time Argues for having a way to do many things at once Finally, we often run many programs all at once And assignment A6 is filled with such concurrency!

What is a Thread? 4 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... n Garbage collection runs in a background thread n GUIs have a separate thread that listens for events and dispatches upcalls Today: learn to create new threads of our own and see threads in action in assignment A6.

What is a Thread? 5 A thread is a kind of object that independently computes Needs to be created, like any object Then started. This causes some method (like main()) to be called. It runs side by side with other threads in the same program, and they see the same global data The Mac has an app, Activity Monitor, that shows you what apps are running and how many threads each has. We show you this on Gries s laptop. The PC should have a similar app. Find it and play with it! On Gries s computer at the moment, the Mail app 22 threads, Safari has 13. DropBox has 41. Eclipse has 34.

Concurrency 6 Concurrency refers to a single program in which several threads are running simultaneously Special problems arise They see the same data and hence can interfere with each other, e.g. one thread modifies a complex structure like a heap while another is trying to read it

Class Thread in Java 7 Threads are instances of class Thread Can create many, but they consume space & time The Java Virtual Machine created the Thread that executes your method main. Threads have a priority Higher priority Threads are executed preferentially A newly created Thread has initial priority equal to the Thread that created it (but can change)

Runnable object, running in a new Thread 8 class PrimeRun implements Runnable { long a, b; PrimeRun(long a, long b) { this.a= a; this.b= b; public void run() { // compute primes // in a..b... PrimeRun p= new PrimeRun(143, 195); new Thread(p).start(); run() Runnable PrimeRun@... tostring() run() Object PrimeRun Method start() will call p s method run() in the new thread of execution

Runnable object, running in a new Thread 9 class PrimeRun implements Runnable { long a, b; PrimeRun(long a, long b) { this.a= a; this.b= b; public void run() { // compute primes // in a..b... PrimeRun p= new PrimeRun(143, 195); p.run(); run() Runnable PrimeRun@... tostring() run() Object PrimeRun No new thread. run() runs in same thread as its caller

10 Creating a new Thread (Method 2) class PrimeThread extends Thread { long a, b; PrimeThread(long a, long b) { this.a= a; this.b= b; public void run() { // compute primes // a..b... run() Runnable PT@... tostring() interrupt() isalive() getstate() run() Object Thread PT PrimeThread p= new PrimeThread(143, 195); p.start(); Class Thread has methods to allow more control over threads

Class Thread has methods for handling threads 11 run() Runnable You can interrupt a thread, maintain a group of threads, set/change its priority, sleep it for a while, etc. PT@6667f34e tostring() interrupt() isalive() getstate() Object Thread run() PT Class PT extends Thread, which implements Runnable

Now to Assignment A6B: Shipping Game 12 In a nut shell: Bunch of cities with roads between them (a graph) Parcels sitting at cities, have to be trucked to other cities Trucks, all at a city called Truck Depot, have to be used to move each parcel from its start city to its destination city. Then return Trucks to the Home Depot YOU have to write the program that tells the Trucks what to do! Efficiency is important! Use shortest paths where possible. We DEMO A6B

Assignment A6B: Shipping Game 13 Assignment A6 is developed Michael (Shnik) Patashnik Undergrad TA A&S, studying Economics and CS Other CS2110 staff involved: Eric Chahin, Alex Fusco, Aaron Nelson, Alexandra Anderson. Which one of you will be the next one to help us develop our assignments?

Ideas for A6b 14 Spend a lot of time thinking about the design, looking at specs of Truck, Parcel, manager, etc. Look at class diagram on page 7 of the handout. Given a truck that has to pickup a Parcel, need to find a quickest/shortest path to where Parcel is. Dfs and bfs won t do. Probably need a version of shortest-path algorithm from a start node to another. Each Truck has a field UserData in which you can store anything you wish. E.g. a path from current location to destination of the Parcel it is carrying. Each Parcel also has a UserData field

You class MyManager extends game.manager 15 We don t give you Java source files. We give you only the.class files and good specs of the classes. Specs are in Data/doc We demo looking at API specs

Your main task 16 public class YourManager extends Manager { public @Override void run() { Look at map, parcels truck, do preprocessing and give Trucks their initial instructions public @Override void trucknotification(truck t, Notification message) { Called when event happens with Truck t it waited to long and is prodding, it arrived at a city, there s a parcel at the city, etc. This method should give the truck directions on how to proceed.

Manager and trucks run in their own thread 17 public class YourManager extends Manager { public @Override void run() { public @Override void trucknotification(truck t, Notification mess) {... Your manager Truck 1 Truck 2 thread thread thread Make sure shared variables don t cause problems. E.g. Two Trucks try to take the same Parcel

A6 Efficiency 18 You want to get the best score possible! How much you do, what you do, depends your time constraints, your abilities, whether your find this assignment fun. Here are things to consider. It costs for a Truck to wait It costs for a Truck to travel It costs for a Truck to pick up and drop a Parcel A LOT is gained by dropping a Parcel at its destination Parcel Payoff is a LOT more if the truck that delivers it has the same color as the Parcel.

Big problem with shared data: a small example 19 Suppose x is initially 5 Thread t1 Thread t2 x= x + 1; x= x + 1;... after finishing, x = 6! Why? Sequence: t1 evaluates x+1 to get 6 t2 evaluates x+1 to get 6 t2 stores its value 6 in x t1 stores its value 6 in x We need ways to prevent this from happening. There are several. Here, we explain only Java s synchronization mechanism Getting concurrent programs right is much much harder!

The synchronized block 20 Stack<String> s= new Stack<String>(); if ( ) { This is a block of code synchronized(s) { This is a synchronized block of code A block synchronized on an object prohibits any other thread from accessing the object while the block is being executed. The synchronized block is a primary tool for eliminating shared data problems. (There are others)

Solution with synchronization 21 private Stack<String> s= new Stack<String>(); public void dosomething() { String st; synchronized (s) { if (s.isempty()) return; st= s.pop(); synchronized block code to do something with st Put critical operations in a synchronized block The stack object acts as a lock Only one thread can own the lock at a time Make synchronized blocks as small as possible

Solution Locking 22 You can lock on any object, including this public void dosomething(){ synchronized (this) { body Note: the whole body is synchronized on this. There s a shorthand for this in Java is equivalent to public synchronized void dosomething(){ body

Solving the shared x= x+1 problem 23 public class Ctr { int x= 0; public synchronized void inc { x= x + 1; public class T extends Thread { Ctr ctr; public T(Ctr c) { ctr= c; public void run() { ctr.inc(); Ctr c= new Ctr(); Thread t1= new T(c); Thread t2= new T(c); T1.start(); T2.start(); T1 and T2 share a counter object. They can try to increment x at the same time (by calling inc), but one must wait.

Threads and synchronization in A6 24 A lot of synchronization happens behind the scenes in A6: The manager that you write is a Thread. Each Truck is a Thread. Depending on your implementation, you may or may not have to use synchronization primitives in your part. Most of you will not use synchronized blocks at all. Just be careful and ask yourself whether concurrency can cause problems. E.g. can two trucks try to pick up the same Parcel at the same time?

Manager and trucks run in their own thread 25 public class YourManager extends Manager { public @Override void run() { public @Override void trucknotification(truck t, Notification mess) {... Your manager Truck 1 Truck 2 thread thread thread Make sure shared variables don t cause problems. E.g. Two Trucks try to take the same Parcel

Your method run(): Preprocessing 26 for Parcel p do Choose a truck t to deliver p. Store p in a data structure in t s user data. end How to chose? It s up to you. How to store data? It s up to you.

Your trucknotification(truck t, Notification mess) 27 // Always start with first if if preprocessing not done then return; if there are no Undelivered Parcels then Route t home and return; if t holding a parcel then Route t to parcel s destination, drop it off if there else Find next parcel assigned to t, route to that parcel Remember: several threads (Trucks) may be executing this at the same time. If shared data structures used, must make sure concurrency doesn t create problems Truck t calls this method to say that it has done something or it is waiting for further instructions.

Synchronized collections 28 Study class Collections and the methods before working on the assignment: synchronizedcollection synchronizedset synchronizedsortedset synchronizedlist synchronizedmap synchronizedsortedmap