COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this?

Slides:



Advertisements
Similar presentations
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Advertisements

Practice Session 7 Synchronization Liveness Guarded Methods Model
CS 11 java track: lecture 7 This week: Web tutorial:
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Avishai Wool lecture Introduction to Systems Programming Lecture 4 Inter-Process / Inter-Thread Communication.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Multithreading.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
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)
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
111 © 2002, Cisco Systems, Inc. All rights reserved.
An Intro to Programming with C# Threads Presentation by: Jason Bender, Garrett Lund, Ben Gamble, Michael Calvo, and Jeff Corbell.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Producer-Consumer Problem The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue.bufferqueue.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
Threads.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
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.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Multi-Threading in Java
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Dr.A.Srinivas PES Institute of Technology Bangalore, India
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
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.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Ivan Marsic Rutgers University LECTURE 19: Concurrent Programming.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
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.
Concurrent Programming in JAVA Steve Pruett - Introduction Jaime Mendez – Thread Creation Adrian Garcia – Thread Management Eric Orozco – Thread Safety.
Distributed and Parallel Processing George Wells.
Tutorial 2: Homework 1 and Project 1
CSCD 330 Network Programming
Multithreading / Concurrency
Multi Threading.
CS703 – Advanced Operating Systems
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Synchronization Lecture 23 – Fall 2017.
Multithreading.
Producer-Consumer Problem
Multithreading.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Computer Science 2 06A-Java Multithreading
NETWORK PROGRAMMING CNET 441
CS333 Intro to Operating Systems
Threads and Multithreading
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Synchronization and liveness
Presentation transcript:

COS 461 Fall 1997 Concurrent Programming u Traditional programs do one thing at a time. u Concurrent programs do several things at once. u Why do this? –exploit parallel hardware –defer work (“to-do list”) –interface to slow device (disk, printer, net) –interface with person –handle many network clients at once

COS 461 Fall 1997 Expressing Concurrency u Use a thread for each concurrent activity. u Multiple threads can run within a single program. –appear to run at the same time –really, they take turns running –scheduling happens automatically u A sequential program is a program with one thread in it.

COS 461 Fall 1997 Starting a Thread: Method 1 class MyThread extends java.lang.Thread { … public void run() { // code you want the thread to execute } // start a thread MyThread t = new MyThread(args); t.start();

COS 461 Fall 1997 Starting a Thread: Method 2 class MyClass implements java.lang.Runnable { … public void run() { // code you want the thread to execute } // start a thread MyClass m = new MyClass(args) Thread t = new Thread(m); t.start();

COS 461 Fall 1997 Other Thread Operations u Thread.currentThread gets the identity of the currently-running thread. u Thread.sleep(millis) puts the calling thread to sleep for millis milliseconds. u t.stop() kills thread t. u thread suicide: Thread.currentThread.stop(); –or return from run

COS 461 Fall 1997 Shared Memory u Threads in the same program share memory. –Good: can communicate quickly and easily –bad: can stomp each other’s data structures »horrible bugs! u Threads in a program share statics and newed up objects. u Private versions of arguments and locals.

COS 461 Fall 1997 Deferring Work with Threads class DeferredGradeReport extends Thread { private String student; public DeferredGradeReport(String who) { student = who; start(); } public void run() { int grade = calculateGrade(student); sendGradeToStudent(student, grade); }

COS 461 Fall 1997 Why are Threads Tricky? u Single thread: things change only because the program changes them u multi-threaded: things can change “on their own” x = y; if(x != y){ // die horribly } x = 17;

COS 461 Fall 1997 Another Thread-Related Disaster class C { private int x = 3; public void increment() { int r = x; ++r; x = r; } r = x; ++r; x = r; r = x; ++r; x = r; thread Athread B

COS 461 Fall 1997 Mutual Exclusion u protect data from “outside meddling” u use Java’s synchronized keyword class C { private int x = 3; public synchronized void increment() { int r = x; ++r; x = r; }

COS 461 Fall 1997 Synchronized: Details u synchronized method holds a “lock” on the object that the method is invoked on u if lock is unavailable, you’re put to sleep until you can get it u lock doesn’t prevent access to data, it only prevents locking return call return call SLEEPSLEEP

COS 461 Fall 1997 Synchronized: Details u same thread can acquire the same lock multiple times –recursive synchronized methods “work” u also, synchronized statement in Java C c = new C(); … synchronized(c){ ++(c.x); }

COS 461 Fall 1997 Deadlock u A waiting for B; B waiting for A u we’re stuck, forever class LLitem { private LLitem next, prev; synchronized void remove(){ synchronized(next){ next->prev = prev; } synchronized(prev){ prev->next = next; }

COS 461 Fall 1997 Avoiding Deadlock u key idea: avoid cycles of waiting u can do use special-case design, then convince yourself it’s correct u usually, follow two simple rules –never lock two objects of the same class at the same time –if class C was written before class D, code in C never locks a D object (not even indirectly)

COS 461 Fall 1997 Example: Blocking Queue (1.0) public class BlockingQueue extends Queue { public synchronized void put(Object o) { super.put(o); } public synchronized Object get() { if(super.empty()) return null; else return super.get(); }

COS 461 Fall 1997 Using BlockingQueue 1.0 // get from BlockingQueue bq Object o; do{ o = bq.get(); }while(o == null); Problem: waste CPU time calling get() over and over Solution: when queue is empty, get() should block the calling thread

COS 461 Fall 1997 BlockingQueue 2.0 public class BlockingQueue extends Queue { public synchronized void put(Object o) { super.put(o); } public synchronized Object get() { while(super.empty()) Thread.yield(); return super.get(); } Deadlock!

COS 461 Fall 1997 BlockingQueue 3.0 public class BlockingQueue extends Queue { // put omitted public /*synchronized*/ Object get() { while(super.empty()) Thread.yield(); synchronized(this) { return super.get(); } Sometimes returns null

COS 461 Fall 1997 BlockingQueue 4.0 public class BlockingQueue extends Queue { public Object get() { Object ret; do{ while(super.empty()) Thread.yield(); synchronized(this) { ret = super.get(); } }while(ret == null); return ret; } Works, but inefficient

COS 461 Fall 1997 Solution: wait/notify u idea: let a thread wait while holding a lock –temporarily gives up lock while sleeping –awakened when another thread causes something to change u Java syntax –wait(): sleeps temporarily (giving up lock) –notify(): wakes up one sleeper –notifyAll() wakes up all sleepers

COS 461 Fall 1997 BlockingQueue: Solution public class BlockingQueue extends Queue { public synchronized void put(Object o) { super.put(o); notify(); } public synchronized Object get() { while(super.empty()) wait(); return super.get(); }

COS 461 Fall 1997 Wait/Notify Details u several threads can wait simultaneously u wait() releases lock, waits for wakeup, then reacquires lock before continuing u wake-up not immediate, so condition might not be true when thread returns from wait() –check for condition in while-loop u OK to wake up too many threads; deadly to wake up too few –when in doubt, notifyAll()