System Programming Practical Session 7

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Practice Session 7 Synchronization Liveness Guarded Methods Model
System Programming Practical Session 5 Liveness, Guarded Methods, and Thread Timing.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Definitions Process – An executing program
© 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.
Threads Written by Amir Kirsh, Dr. Yaron Kanza. Edited by Liron Blecher.
Multithreading.
1 CSCI 6900: Design, Implementation, and Verification of Concurrent Software Eileen Kraemer August 19 th, 2010 The University of Georgia.
1 CSCD 330 Network Programming Lecture 13 More Client-Server Programming Sometime in 2014 Reading: References at end of Lecture.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threads some important concepts Simon Lynch
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Practice Session 8 Blocking queues Producers-Consumers pattern Semaphore Futures and Callables Advanced Thread Synchronization Methods CountDownLatch Thread.
Threading Eriq Muhammad Adams J
Synchronizing threads, thread pools, etc.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
System Programming Practical Session 4: Concurrency / Safety.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
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.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
תכנות מערכות תרגול 1 נושאי התרגול: - חשבון משתמש Linux - Threads.
Multithreading and Garbage Collection Session 16.
System Programming Practical Session 4: Concurrency / Safety.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Advanced Tools for Multi- Threads Programming Avshalom Elmalech Eliahu Khalastchi 2010.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
CSCD 330 Network Programming
Threads in Java Two ways to start a thread
Multithreading / Concurrency
Multi Threading.
Multithreading.
Practice Session 8 Lockfree LinkedList Blocking queues
Java Concurrency.
Multithreading Chapter 9.
Multithreading in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Java Concurrency.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Threads and Multithreading
CSCD 330 Network Programming
Philosopher Example class PhilosophersShare {
Software Engineering and Architecture
Threads CSE451 Andrew Whitaker TODO: print handouts for AspectRatio.
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Synchronization and liveness
Presentation transcript:

System Programming Practical Session 7 Synchronization, Liveness, Guarded Methods, and Thread Timing

Synchronization A mechanism allowing safely accessing shared resources. A thread accessing a synchronized method locks the object. The object cannot be accessed by other threads while it is locked.

Synchronization 1. Class Even{ 2. private long n = 0; 3.  public  long next(){  4.        n++;  5.        n++;  6.        return n;  7.     } 8. }

Synchronization 1. Class Even{ 2. private long n = 0; 3.  public synchronized long next(){  4.        n++;  5.        n++;  6.        return n;  7.     } 8. }

Synchronizing a block public int foo() { // do something safe          synchronized(this) {             // do something             return 9;          }     }

Solution to safety problem Printer Example (from practical session 1) class Printer {     Printer() {}     /**      * @param i line number      * @param s the string to concatenate 40 times      */     public synchronized void printALine(int i, String s) {         System.out.print(i + ") ");         for (int j = 0; j < 40; j++) {             System.out.print(s);         }         System.out.println();     } }

public class GoodSynchronization{  public static void main(String[] a) {        Printer p = new Printer();        Thread t1 = new Thread( new SimpleAsynchronousTask("a", p) );       Thread t2 = new Thread( new SimpleAsynchronousTask("b", p) );          t1.start();  // prints some lines of aaaa         t2.start();  // prints some lines of bbbb  }   } class SimpleAsynchronousTask implements Runnable {     Printer m_p;     String m_name;     public SimpleAsynchronousTask(String name, Printer p) {         m_p = p;         m_name = name;     }     public void run() {         for (int i = 0; i<50; i++) {             m_p.printALine(i, m_name);         }  } }

Wrong solution #1 public class BadSynchronization2     public static void main(String[] a) {         Printer p1 = new Printer();         Printer p2 = new Printer();         Thread t1 = new Thread( new SimpleAsynchronousTask("a", p1) );         Thread t2 = new Thread( new SimpleAsynchronousTask("b", p2) );           t1.start();  // prints some lines of aaaa         t2.start();  // prints some lines of bbbb     } } class SimpleAsynchronousTask implements Runnable { .....the same like GoodSynchronization.java class Printer {

Wrong solution #2 (no printer object) class BadSynchronization {     public static void main(String[] a) {         Thread t1 = new Thread( new SimpleAsynchronousTask("a") );         Thread t2 = new Thread( new SimpleAsynchronousTask("b") );         t1.start();  // prints some lines of aaaa         t2.start();  // prints some lines of bbbb     } }   class SimpleAsynchronousTask implements Runnable { .....the same like GoodSynchronization.java     public synchronized void printALine(int i, String s) {         System.out.print(i + ") ");         for (int j = 0; j < 40; j++) System.out.print(s);         System.out.println();

Liveness A concurrent application's ability to execute in a timely manner. Liveness problems: Deadlock Starvation Livelock

Deadlock Thread 2 Thread 1 acquire Scanner acquire Printer use scanner use printer release Scanner release Printer Thread 1 acquire Printer acquire Scanner use printer use scanner release Printer release Scanner Thread 1 Thread 2

public class Deadlock {   public static void main(String[] args) {     final Object resource1 = “Printer";   final Object resource2 = “Scanner";     Thread t1 = new Thread(new Runnable() {       public void run() {          synchronized(resource1) {            System.out.println("Thread 1: locked resource 1");            try {Thread.sleep(50);} catch (InterruptedException e){}                    synchronized(resource2) {                System.out.println("Thread 1: locked resource 2");     }/* release resource2 */ }/* release resource1 */  } } );      Thread t2 = new Thread(new Runnable() {          synchronized(resource2) {            System.out.println("Thread 2: locked resource 2");              try{Thread.sleep(50);} catch(InterruptedException e){}            synchronized(resource1) {              System.out.println("Thread 2: locked resource 1");      }/* release resource1 */ }/* release resource2 */  } } );      t1.start();      t2.start();    } }

Resource Ordering All threads acquire the locks in the same order. acquire Printer acquire Scanner use printer use scanner release Printer release Scanner Thread 2 acquire Printer acquire Scanner use printer use scanner release Printer release Scanner

Starvation Some threads are waiting forever for resources that are used by other threads.

Starvation Some threads are waiting forever for resources that are used by other threads. Example1: A solution to the dinning philosophers problem in which philosophers 1,3,5 never eat, and philosophers 2,4 eat whenever they want. 3 2 4 1 5

Starvation Example 2: Threads with priority. Each thread has a priority: Low or High. Low priority threads execute only if there are no high priority threads. High priority threads keep coming. High Low

Livelock Threads are unable to make progress although they are not blocked.

Livelock Threads are unable to make progress although they are not blocked. Example: two threads trying to pass a shared corridor. Thread protocol: if there is an obstacle, then move aside.

Livelock Threads are unable to make progress although they are not blocked. Example: two threads trying to pass a shared corridor. Thread protocol: if there is an obstacle, then move aside.

Guarded Methods The guarded method model delays the execution of a thread until a condition is satisfied. A thread that is unable to proceed, waits for condition change made by another thread.

Basic Thread Timing Example Each thread is assigned a number from {1,2,…,k}. In any point in time, only threads assigned a certain number run. Other threads wait. 1 3

Basic Thread Timing Example Each thread is assigned a number from {1,2,…,k}. In any point in time, only threads assigned a certain number run. Other threads wait. 1 3

class Checker {     private  int m_num;     public Checker(int num) {         this.m_num = num;     }     public synchronized void  change(int num) {     public synchronized boolean check(int num){         return (num == this.m_num); }

public class Threads01 { public static void main(String[] args) {     Checker checkerObject = new Checker(0);         Thread t[] = new Thread[9]; for (int i = 0; i < t.length ; i++) t[i] = new Thread(new SleepThread(i/3+1, "NO. " +(i+1)+ " done, was waiting for "+(i/3+1), checkerObject)); for (int i = 0; i < t.length; i++) t[i].start();     try {  Thread.sleep(1000); checkerObject.change(1);  Thread.sleep(1000); checkerObject.change(3);  checkerObject.change(2);     } catch (InterruptedException e) {}   } }

Solution #1: Busy Waiting class SleepThread implements Runnable {     private int m_num;     private String m_strToPrintWhenDone;     private Checker m_checkerObject;     SleepThread(int num, String strToPrintWhenDone,  Checker checkerObject) {         this.m_num = num;         this.m_strToPrintWhenDone = strToPrintWhenDone;         this.m_checkerObject = checkerObject;     }     public void run()  { /* busy waiting */         while (!this.m_checkerObject.check(this.m_num)) ;         System.out.println(this.m_strToPrintWhenDone); }

Solution #2: Sleep and Check class SleepThread implements Runnable {     private int m_num;     private String m_strToPrintWhenDone;     private Checker m_checkerObject;     SleepThread(int num, String strToPrintWhenDone,  Checker checkerObject) {         this.m_num = num;         this.m_strToPrintWhenDone = strToPrintWhenDone;         this.m_checkerObject = checkerObject;     }     public void run()  {         while (!this.m_checkerObject.check(this.m_num))         {             try {                 Thread.sleep(100);             } catch (InterruptedException e) {}         }         System.out.println(this.m_strToPrintWhenDone); }

Solution #3: Wait and Notify class SleepThread implements Runnable { ………   public void run()     {         this.m_checkerObject.returnWhenCheckIsTrue(m_num);           System.out.println(m_strToPrintWhenDone);     } } class Checker {     private int m_num;     public Checker(int num) {       this.m_num = num;     }       public synchronized void change(int num){         this.m_num = num;         this.notifyAll();     }     public synchronized void returnWhenCheckIsTrue(int num) {         while (num != m_num) {             try {                  this.wait();             } catch (InterruptedException e) {}         }   } }

Tips Use a while loop (and not an if condition) to check the precondition notify() Vs. notifyAll() - which of them should you use? When calling wait(), notifyAll() or notify() on an object, make sure the calling thread holds the object's lock. Notice that if you do not hold the object's lock you will receive an illegal monitor runtime exception. After performing a wait call on the object, the thread releases the object's lock. Furthermore, before exiting the wait set of the object, the thread must re-lock the object A thread that releases an object's, lock will NOT release other locks it has

Advanced Synchronization Tools CountDownLatch Constructor: CountDownLatch(int value) Methods: void countDown() Decrements the latch value by 1. void await() Causes the current thread to wait until the latch has counted down to zero.

import java.util.concurrent.*;   public class Threads {     public static void main(String[] args)     {         CountDownLatch latchObject = new CountDownLatch (3);           Server s =  new Server (latchObject);         Client c1 = new Client (1, latchObject);         Client c2 = new Client (2, latchObject);         Client c3 = new Client (3, latchObject);      Thread t1=new Thread(s);      Thread t2=new Thread(c1);      Thread t3=new Thread(c2);      Thread t4=new Thread(c3);         t1.start();         t2.start();         t3.start();           t4.start();     } }

class Server implements Runnable {   private CountDownLatch m_latchObject;      public Server(CountDownLatch latchObject)   {       m_latchObject = latchObject;   }      public void run ()       synchronized (System.out)       {           System.out.println("Server initialized");       }         try {       m_latchObject.await();       } catch (InterruptedException e)           return;       }       System.out.println("Server finished");   } }

class Client implements Runnable {     private int m_id;    private CountDownLatch m_latchObject;     public Client(int id, CountDownLatch latchObject){         m_id = id;         m_latchObject = latchObject;     }          public void run () {         synchronized (System.out) {             System.out.println("Client #" + m_id + " started");         }         try { Thread.sleep(200); } catch (InterruptedException e) {}         synchronized (System.out){             System.out.println("Client #" + m_id + " doing something");         }               try {   Thread.sleep(200); } catch (InterruptedException e) {}             System.out.println("Client #" + m_id + " finished");         m_latchObject.countDown();                        } }