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

Similar documents
Unit - IV Multi-Threading

Threads Chate Patanothai

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Concurrent Programming using Threads

7. MULTITHREDED PROGRAMMING

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

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

Software Practice 1 - Multithreading

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

Module - 4 Multi-Threaded Programming

Multithreaded Programming

Java Threads. Written by John Bell for CS 342, Spring 2018

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

CS 556 Distributed Systems

Note: Each loop has 5 iterations in the ThreeLoopTest program.

CS 351 Design of Large Programs Threads and Concurrency

Multithreaded Programming

Concurrent Programming

Multithread Computing

Object Oriented Programming (II-Year CSE II-Sem-R09)

Performance Throughput Utilization of system resources

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

Concurrency - Topics. Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads

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

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Contents. 6-1 Copyright (c) N. Afshartous

Object Oriented Programming. Week 10 Part 1 Threads

Threads Questions Important Questions

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

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

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

CIS233J Java Programming II. Threads

Introduction to Java Threads

COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE

Model Requirements and JAVA Programs MVP 2 1

Definition: A thread is a single sequential flow of control within a program.

Advanced Concepts of Programming

Chair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency

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

Animation Part 2: MoveableShape interface & Multithreading

CPS 506 Comparative Programming Languages. Programming Language Paradigms

Concurrency in Java Prof. Stephen A. Edwards

CMSC 330: Organization of Programming Languages

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

Advanced Programming Concurrency

Multi-threading in Java. Jeff HUANG

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

SUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams

Multithreading Pearson Education, Inc. All rights reserved.

public class Shared0 { private static int x = 0, y = 0;

wait with priority An enhanced version of the wait operation accepts an optional priority argument:

JAVA. Lab 12 & 13: Multithreading

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CS 10: Problem solving via Object Oriented Programming Winter 2017

Unit III Rupali Sherekar 2017

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

Threads in Java (Deitel & Deitel)

Chapter 32 Multithreading and Parallel Programming

Reintroduction to Concurrency

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

Java Threads. Introduction to Java Threads

Handling Multithreading Approach Using Java Nikita Goel, Vijaya Laxmi, Ankur Saxena Amity University Sector-125, Noida UP India

Contents. G53SRP: Java Threads. Definition. Why we need it. A Simple Embedded System. Why we need it. Java Threads 24/09/2009 G53SRP 1 ADC

What is a Thread? Individual and separate unit of execution that is part of a process. multiple threads can work together to accomplish a common goal

04-Java Multithreading

Programming in Parallel COMP755

Chapter 19 Multithreading

SMD149 - Operating Systems

Programming Language Concepts: Lecture 11

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

UNIT V CONCURRENT PROGRAMMING

Amity School of Engineering

Parallel Programming Languages COMP360

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

What is a thread anyway?

MULTI-THREADING

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

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

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

CS360 Lecture 12 Multithreading

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

JAVA - MULTITHREADING

Multithreading using Java. Dr. Ferdin Joe John Joseph

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

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

Network Programming COSC 1176/1179. Lecture 6 Concurrent Programming (2)

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

Object-Oriented Programming Concepts-15CS45

THREADS AND CONCURRENCY

Techniques of Java Programming: Concurrent Programming in Java

Multi-threaded programming in Java

CS193k, Stanford Handout #8. Threads 3

Threads, Concurrency, and Parallelism

Java Threads. COMP 585 Noteset #2 1

CS 159: Parallel Processing

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

Faculty of Computers & Information Computer Science Department

Java Threads Instruct or: M Maina k Ch k Chaudh dh i ur ac.in in 1

THREADS & CONCURRENCY

Transcription:

Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running more than one job at time by allowing jobs to share the CPU (time slicing) PContet switch: switching the CPU between jobs; requires saving one job s state while restoring another job s state PPreemptive multitasking: Operating system schedules the contet switch based on a maimum time slice < Uni, all varieties (at the ess level) < Windows 95/98/NT PCooperative multitasking: task must relinquish the CPU < Windows 3.1 < Solaris green threads Threads Slide 2 of 30 Process aka heavy weight ess Process Creation Programs become esses PProgram whose eecution has started & not yet terminated parent child POne main per ess (with one caveat) Pfork( ) duplicates a ess (data and instructions) PProcesses do not directly share data < Identical esses have distinct data < Communication, data sharing, and synchronization are OS services PCalled heavy weight because contet switch is etensive fork esses created from 1 ram do not share data. forking a ess dubplicates data; data still not shared Threads Slide 3 of 30 Threads Slide 4 of 30 Thread aka light weight ess or thread of control Thread Eample Concurrent function/method eecution P Threads originate from a single ram < A thread is a concurrent flow of eecution of a task in a ram < They are the concurrent eecution of functions or methods within the ram < Do not duplicate any code or data < Threads share global data (instance variables in Java ) < Thread contet switch time is less than for esses because there is less state to save and restore do to the shared data < A single ess may be multithreaded P Two types of threads < System level implemented in the OS (kernel) < Application level implemented in the application (language) but still requires OS support main() threadstart(fill) threadstart(empty) fill()... empty()... ess ess empty fill data threads empty fill data Threads Slide 5 of 30 Threads Slide 6 of 30

Thread States Similar to Uni ess states P new created but not scheduled to run P ready scheduled and capable of running P running: has the CPU runnable P blocked: waiting for a service (e.g., an I/O operation) to finish P asleep: called the sleep() method; sleeps for set time P suspend: called the suspend() method; must resume() P waiting: P dead: called the wait() method; must notify() or notifyall() run() ends or stop() called; cannot restart Threads Slide 7 of 30 Thread State Changes Dynamic Thread behavior running waiting suspend asleep blocked new start( ) ready run( ) completes or stop( )* dead * deprecated at 1.2 Threads Slide 8 of 30 Basic Thread Methods Defined in java.lang.thread Petends Thread < Thread( ) constructor < override the run( ) method Pimplements Runnable < Thread(Runnable object) create and use with Thread object < implement the run( ) method Pvoid run( ) concurrent eecution (called by scheduler) Pvoid start( ) schedules thread, scheduler calls run( ) Pvoid join( ) t.join( ) waits for thread t to finish < join(long ms)as above but continues after ms milliseconds Pvoid sleep(n) pauses calling thread for m milliseconds < sleep(m, n) sleeps thread for m millisecons + n nanoseconds Threads Slide 9 of 30 Thread Methods Continued P void yield( ) voluntarily relinquishes the CPU P void wait( ) thread relinquishes all locks and self-blocks P void notify( ) restarts a thread blocked on a wait() P void notifyall( ) restarts all threads blocked with a wait() P void destroy( ) terminates a thread without cleanup P boolean isalive( ) true if the thread is started & not terminated P void interrupt( ) interrupts this thread P boolean isinterrupted( ) is specified thread interrupted P boolean interrupted( ) static: was current thread interrupted P InteruptedEception thrown by sleep( ) and wait( ) Threads Slide 10 of 30 Scheduling Threads To Run Concurrency in Java rams PYou can call a thread s run method, but that does not run it concurrently PA dead thread may not be restarted or recycled < But you can call a dead thread object s other methods public class MyThread etends Thread... Thread T = new MyThread ( ); T.start( ); // inherited from Thread Threads Slide 11 of 30 Terminating Threads When Threads quit // do something useful boolean done = false; while (! done) if (some condition is met) done = true; // do something useful Threads Slide 12 of 30

Multitasking Concepts A task may be either a thread or a ess P Critical resource a limited (finite number or amount) commodity that a task needs to complete its task P Critical section a code segment in a task that uses a critical resource P Mutual eclusion a protocol to limit the number of tasks in a critical section < when no task is in a critical section, a requesting task is not delayed < when two tasks compete for a critical section, the selection cannot be postponed indefinitely < no task can prevent another from entering its critical section indefinitely P Deadlock 2 or more tasks each have a mutual eclusion lock on a resource needed by another Threads Slide 13 of 30 Multitasking Concepts Continued P Starvation a task is never allowed access to a critical resource; it is never allowed to run to completion P Atomic test and set an uninterleavable instruction that tests and sets the value of a variable P Fairness contention for a critical resource is resolved < weak fairness: if a task continuously makes a request, it is eventually satisfied < strong fairness: if a task makes a request infinitely often, it is eventually satisfied < linear waiting: if a task makes a request, it is granted before any other task is granted the same request more than once < FIFO waiting: if a task makes a request, it will be granted before that of a task making a later request Threads Slide 14 of 30 Competing Tasks Mutual eclusion eample Mutual Eclusion In Java synchronized methods (Hoare s Monitors) mutual eclusion widgets = N + widgets inventroy update task if (inuse == false) inuse = true else block widgets 10 inuse = false critical resource atomic test and set instruction widgets = widgets - 1 POS task Threads Slide 15 of 30 P synchronized (keyword) at most one Thread allowed in a synchronized method (others are blocked) synchronized public void Insert( ) // critical section PEach class and each object with one or more synchronized methods has one lock and one queue < Static methods use the class s lock < Non-static methods use the per object lock < A thread entering a synchronized method acquires the object s lock and other threads entering any of the object s synchronized methods are suspended and placed on the wait-queue Threads Slide 16 of 30 Waiting Threads Two places-- two selection algorithms Simple Mutual Eclusion Serializing access (compare with slide 15) T 9 T 8 queue (FIFO) T 3 T 7 T 1 T 2 T 6 wait( ) T 5 T 0 T 4 notifyall( ) synchronized Monitor-- synchronized method Threads Slide 17 of 30 public class Inventory private int widgets; // critical resource synchronized public void update(int N) widgets += N; synchronized public void sell( ) widgets -= 1; // class Inventory Threads Slide 18 of 30

Fine-grained Mutual Eclusion (synchronized blocks) P Create an object and use it s lock to provide mutual eclusion on a block of code P You may use the lock object s methods and data class Lock... Lock BlockLock = new Lock( ); void public somemethod( )... synchronized (BlockLock) // critical section... // stylistically preferred void public mymethod( )... synchronized(this) // critical section... Threads Slide 19 of 30 The Producer/Consumer Problem (the bounded buffer problem) P Producer threads write data to a finite Buffer object P Consumer threads read from the Buffer object P Buffer variables that must be protected < counter how may elements in Buffer < front insert location in Buffer < back remove location in Buffer P Producers must increment counter and front P Consumer must decrement counter and increment back P Two threads cannot change a variable at the same time P One thread cannot change a variable while another thread tests its value Threads Slide 20 of 30 Producer/Consumer Illustrated Buffer State Diagram OMT state diagram from the dynamic model producer1 producer2 producer3 counter == 4 back Inserting store / insert [counter = bufsize] eit / stored store / insert [counter < bufsize] Buffer Empty Partially Filled Filled Consumer front Compare with PipedInputStream Buffer object & PipedOutputStream Threads Slide 21 of 30 [counter > 0] retrieve / remove Retrieving eit / retrieved [counter = 0] retrieve / remove Threads Slide 22 of 30 Implementing Mutual Eclusion Java synchronization features (See Buffer.java) Referencing A Common Object See Producer.java synchronized public void insert while (counter == bufsize) wait( ); put stuff in the Buffer counter++; notifyall( ); synchronized public int remove while (counter == 0) wait( ); take stuff out of the Buffer counter--; notifyall( ); public class Producer etends Thread int ID; // used to identify a Producer Buffer StoreBuffer; // shared by all Producers & Consumer public Producer(int id, Buffer Buff) ID = id; StoreBuffer = Buff; while (true) int rand = (int)(4000 * Math.random( )); try Thread.sleep(rand); // simulates work catch (InterruptedEception e) StoreBuffer.Insert(ID, rand); // end class Producer Threads Slide 23 of 30 Threads Slide 24 of 30

Referencing A Common Object See Consumer.java public class Consumer etends Thread Buffer StoreBuffer; public Consumer(Buffer Buff) StoreBuffer = Buff; while (true) int rand = (int)(2000 * Math.random()); try Thread.sleep(rand); // simulates work catch (InterruptedEception e) StoreBuffer.Remove( ); // class Consumer Coordinating Threads See Driver.java public class Driver public static void main(string args[ ]) Buffer buff = new Buffer(); Producer P1 = new Producer(1, buff); Producer P2 = new Producer(2, buff); Producer P3 = new Producer(3, buff); Consumer C = new Consumer(buff); P1.start(); P2.start(); P3.start(); C.start(); // class Driver Threads Slide 25 of 30 Threads Slide 26 of 30 Synchronization Summary Monitors and Java s synchronized Methods Pwait < Can only be called within a synchronized method < Thread blocks and is placed in the object s queue Pnotify / notifyall < Can only be called within a synchronized method < Unblocks a / some Thread(s) waiting for an object s state to change PSynchronization rules < If 2 or more Threads modify an object (i.e., change any instance variables), make the methods that effect the changes synchronized < If a Thread must wait to change an object, it should wait inside the object by calling a synchronized method and then by calling wait < Whenever a thread changes an object, it should call notify or notifyall Threads Slide 27 of 30 The Runnable Interface Multithreading Applets (see DClock.java, Train.java, & ThreadAppProto.java) P Using the Runnable interface < implement Runnable < Override run( ) method < Instantiate a Thread and pass it a reference to the main object public class DClock etends Applet implements Runnable while (true) repaint( ); try Thread.sleep(1000); catch (InterruptedEception e) public void start() if (AppletThread == null) AppletThread = new Thread(this); AppletThread.start( ); Threads Slide 28 of 30 Runnable Interface Eample From class Token (Stratego project) Thread Priorities High priority Threads run before low priority Threads public class Token implements Runnable public void epose(space location) display = true; this.location = location; Thread timer = new Thread(this); timer.start( ); try Thread.sleep(10000); catch (InterruptedEception ie) System.err.println("Timer error"); display = false; location.repaint( ); Threads Slide 29 of 30 P Three defined priorities < MIN_PRIORITY 1 < NORM_PRIORITY 5 < MAX_PRIORITY 10 P Altering thread priority < getpriority( ) < setpriority( ) < Attempting to set a priority that is out of range will result in an IllegalArgumentEception P How priority effects scheduling is implementation dependent Threads Slide 30 of 30