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

Size: px
Start display at page:

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

Transcription

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

2 Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2

3 Outcomes Understand race conditions Critical sections and mutual exclusion Synchronization mechanism synchronized methods, block of code wait() and notify() Understand potential problems busy waiting deadlock livelock 3

4 Thread Scheduling Remember Once a thread is runnable it can be scheduled at any time It is hard to predict the actual ordering With multiple threads, we must ensure that any possible interleaving of threads would still be a correct execution 4

5 Race Conditions If the result of a computation changes depending upon the actual ordering of threads we call it a race condition. Can occur even with very simple concurrent programs. Consider a program that simply increments a single variable, count times the task is divided among multiple threads 5

6 public class RaceCondition extends Thread { private static int counter = 0; public static final int THREADS = 4; public static final int COUNT = ; Race Example public static void main(string[] args){ RaceCondition[] threads = new RaceCondition[THREADS]; for(int i=0;i<threads;i++) { threads[i] = new RaceCondition(); threads[i].start(); try{ for(int i=0;i<threads;i++) threads[i].join(); catch (InterruptedException e) { e.printstacktrace(); System.out.println( Counter: + counter); public void run(){ for(int i=0;i<count/threads;i++) counter++; 6

7 Race Without multiple threads, always correct. With multiple threads, often incorrect! Why? multiple threads modifying the same value counter++ is not atomic Atomic operations A java statement translates to multiple machine level statements the thread can be swapped in the middle of these machine level statements 7

8 The memory hierarchy Speed Cost Size ALU Registers Cache CPU Cache (MB) Main Memory (GB) 8

9 Multi Core possibility ALU Core ALU Core Registers Registers Cache CPU Cache Cache (MB) Main Memory (GB) 9

10 Multi Core possibility 2 ALU Core ALU Core Registers Registers CPU Cache (MB) Main Memory (GB) 10

11 Multi CPU possibility ALU CPU ALU Registers ALU Registers Registers Cache Cache Cache Cache (MB) Cache (MB) CPU Program Main Memory (GB) Data 11

12 Atomic operations and Caching Data is operated on in ALUs register = count; register++; count = register; Thus if a thread is swapped out just before the last statement, and another thread swapped in, then we have a lost update The memory hierarchy caches data values. If multiple threads are using some data, it gets copied into multiple caches this can cause different threads to not see all changes made by other threads! 12

13 Shared mutable state How do we ensure correct behavior? Many problems of synchronization can be traced to data that is concurrently read and written by multiple threads shared mutable state if no thread writes -- no problems For example, the variable count is shared mutable state. Only one thread should modify at a given time, and no thread should read the value during this time. 13

14 Critical Section A section of code that should not be accessed by multiple threads concurrently We need to guarantee mutual exclusion in these sections Java solution: use a lock that only one thread holds at a time also called a monitor any object can be locked 14

15 Synchronized The synchronized keyword can be used to declare a method or block of code as a critical section i.e., only one thread can be executing any statements in that method or block of code. public synchronized int methoda(){...//critical section public int methoda(){... synchronized (someobject) {... //Critical section 15

16 Method vs. block of code When synchronized is used with a block of code, we explicitly specify what object should be used for locking; can arbitrarily limit the critical section can have independent locks for different code. A synchronized method implicitly locks the object (this) on which the method is called the class, in the case of static methods 16

17 (No) Race Condition public class NoRaceCondition extends Thread { private static int counter = 0; public static final int THREADS = 4; public static Object lock = new Object(); public static final int COUNT = ; public static void main(string[] args){ NoRaceCondition[] threads = new NoRaceCondition[THREADS]; for(int i=0;i<threads;i++) { threads[i] = new NoRaceCondition(); threads[i].start(); Note: lock is static. try{ for(int i=0;i<threads;i++) threads[i].join(); catch (InterruptedException e) { e.printstacktrace(); System.out.println( Counter: + counter); public void run(){ for(int i=0;i<count/threads;i++){ synchronized(noracecondition.lock){ counter++; Note: not entire method or for loop! 17

18 Synchronization Any code that is synchronized can only be executed by a thread that holds the appropriate lock Only one thread can hold the lock for a given object Any changes made in a critical section will be visible to all threads once they get the lock (ensured by Java) 18

19 Announcements No class on Monday No labs next week 19

20 Producer-Consumer A very common scenario a producer process creates data a consumer process processes data (and deletes it) e.g., networking, unix pipes, device drivers A shared data structure (buffer) is used to hold data before processing limited size if empty -- consumer waits if full -- produce waits 20

21 Producer-Consumer import java.util.*; public class ProducerConsumer extends Thread{ private static Buffer buffer = new Buffer(); private boolean isconsumer; public ProducerConsumer(boolean isc){isconsumer=isc; public static void main ( String[] args ) { ProducerConsumer consumer = new ProducerConsumer(true); ProducerConsumer producer = new ProducerConsumer(false); consumer.start(); producer.start(); try{ consumer.join(); producer.join(); catch (InterruptedException e) { e.printstacktrace(); // run method 21

22 public void run(){ String s; for(int i=0;i<1000;i++){ try{ if(isconsumer){ s = (String) buffer.removeitem(); System.out.println( Consumed: + s); else { s = Item + i; buffer.additem(s); System.out.println( \t\tproduced: + s); sleep(math.ceil(math.random()*10)) ; catch (InterruptedException e) { e.printstacktrace(); 22

23 Buffer class How should the Buffer class be implemented? The buffer is shared mutable state! We must ensure that producers and consumers do not adversely affect each other. When the producer thread is adding a new entry, the consumer should not remove an entry and vice versa. Assume: entries are all packed in the array (i.e., there are no holes) addition/deletion is done at end of array. 23

24 Potential Solution public class Buffer { public final static int SIZE = 10; private Object [] objects = new Object [ SIZE ]; private int count = 0; public synchronized void additem ( Object object ) { objects [ count ++] = object ; public synchronized Object removeitem () { Object object = objects [--count]; return object ; Note: typo in book! not count-- 24

25 Problem If we simply use synchronized methods, what should we do if buffer is full when adding, or buffer is empty when deleting? We could throw an exception and let the user handle this situation. Not a good solution. Ideally, we should wait for the other process to delete (or add) something HOW? 25

26 public class Buffer {... public void additem ( Object object ) { while (true) { synchronized (this) { Potential Solution 2 if ( count!= SIZE ){ objects [ count ++] = object ; break; public Object removeitem () { Object object; while (true) { synchronized(this) { if(count!= 0 ) { object = objects [--count]; break; return object ; 26

27 Busy-waiting! This works, but it is inefficient The thread continuously consumes resources while waiting for something to happen - called busy waiting We would like the thread to wait until some condition is true. How do we suspend a thread until some condition is potentially true? This is achieved using the wait() and notify () methods. 27

28 Thread States new thread start() Runnable notify() wake up Not Runnable schedule yield() (un)schedule Running sleep() wait() run() terminates uncaught exception terminated

29 wait(), notify(), and notifyall() These methods can be called on any object. The calling thread must own the lock (monitor) for the object When the current thread executes wait(), it becomes not runnable until the thread is woken up due to a call to notify() or notifyall() on the object on which it is waiting the thread is interrupted by some other thread the timeout interval has passed 29

30 The wait() method The calling thread gives up its lock on the object until it is woken up or interrupted wait() waits forever to be woken up by notify() or notifyall () wait(long timeout) waits only for timeout milliseconds wait(long timeout, int nanos) specify interval with greater accuracy When the thread waits, it gives up the lock on the object (but not other locks) The thread only resumes after it has re-acquired the lock on the object on which is called wait. 30

31 Notify methods Calling thread must own the lock on the object notifyall() causes all threads waiting on this object to be woken up notify() causes one (arbitrarily chosen) thread waiting on this object to be woken up Both calls result in the lock on the object to be released one of the newly woken threads will get the lock and be able to move on Repeated waits are necessary to ensure that the necessary conditions have been met 31

32 Producer-Consumer Solution public class Buffer { public final static int SIZE = 10; private Object [] objects = new Object [ SIZE ]; private int count = 0; public synchronized void additem ( Object object ) throws InterruptedException { while ( count == SIZE ) wait (); objects [ count ++] = object ; notifyall (); public synchronized Object removeitem () throws InterruptedException { while ( count == 0 ) wait (); Object object = objects [--count]; notifyall (); return object ; 32

33 Synchronization Examples 33

34 Bank Account Example Create a multi-threaded banking class. Allow threads to deposit; withdraw; getbalance Only one thread should be modifying balance at any time. Multiple threads can be reading balance at the same time. 34

35 Solution Keep a count of current active readers All access to readers is synchronized on the account object. Changes to balance are made only in the changebalance() method which is synchronized on the account object. can only change if there are no current readers note: wait() until this is true note: readers must notify() when done! 35

36 SynchronizedAccount public class SynchronizedAccount { private double balance = 0.0; private int readers = 0; public double getbalance () throws InterruptedException { double amount ; synchronized ( this ) { readers ++; amount = balance ; synchronized ( this ) { if( --readers == 0 ) notifyall (); return amount ; public void deposit ( double amount ) throws InterruptedException { changebalance ( amount ); System.out. println (" Deposited $" + amount + "." );... 36

37 SynchronizedAccount public boolean withdraw ( double amount ) throws InterruptedException { boolean success = changebalance ( -amount ); if( success ) System.out.println (" Withdrew $" + amount + "." ) ; else System.out.println (" Failed to withdraw $" + amount + ": insufficient funds." ); return success ; private synchronized boolean changebalance ( double amount ) throws InterruptedException { boolean success ; while ( readers > 0 ) wait (); if( success = ( balance + amount > 0) ) balance += amount ; return success ; 37

38 Account tester public class TestSynchronizedAccount extends Thread { static final int THREADS = 10; static SynchronizedAccount account = new SynchronizedAccount(); static TestSynchronizedAccount[] threads = new TestSynchronizedAccount[THREADS]; static double netchange[] = new double[threads]; int threadid; public TestSynchronizedAccount(int id) { threadid=id; public static void main(string[] args) { double totalchange=0; try{ for(int i=0;i<threads;i++) { threads[i] = new TestSynchronizedAccount(i); threads[i].start(); for(int i=0;i<threads;i++){ threads[i].join(); totalchange+=netchange[i]; System.out.println("Net Change: " + totalchange + "\tcurrent Balance: "+ account.getbalance()); catch (InterruptedException e) { e.printstacktrace(); 38

39 Account tester (cont.) public void run(){ double totalwithdrawals=0; double amount; try{ for(int i=0;i<10;i++) { amount = (Math.ceil(Math.random()*10000))/100.0; if(math.random() <0.5) { if(testsynchronizedaccount.account.withdraw(amount)) { netchange[i]-=amount; System.out.println("\t\t\tThread " + i + " Withdrew: " + amount); else { TestSynchronizedAccount.account.deposit(amount); netchange[i]+=amount; System.out.println("\t\t\tThread " + i + " Deposited: " + amount); catch (InterruptedException e) { e.printstacktrace(); 39

40 Starvation, Livelock, Deadlock It is possible for the changebalance() method to always be prevented from running by some checkbalance() method Thus deposit/withdrawal can starve A deadlock is a situation where more than one threads are waiting for each other in a circular fashion -- none of them will ever make progress! Another potential problem is livelock, i.e., some thread(s) is making progress, but some others may be blocked indefinitely 40

41 The Dining Philosophers Consider N philosophers that think and eat There is a circular table with N seats and N chopsticks When a philosopher wants to eat she tries to pick up two chopsticks and then eats Once done eating she replaces (after washing of course) the chopsticks. How do we simulate this? There should be no starving philosopher! 41

42 Dining Philosopher (deadlock) public void DeadlockPhilosopher extends Thread { public static final int SEATS = 5; private static boolean [] chopsticks = new boolean [SEATS]; private int seat ; public DeadlockPhilosopher ( int seat ) { this.seat = seat ; public void run () { try { getchopstick ( seat ); Thread.sleep (50) ; getchopstick ( seat - 1 ); catch ( InterruptedException e ) { e. printstacktrace (); eat (); 42

43 Dining Philosophers (cont.) private void getchopstick ( int location ) throws InterruptedException { if( location < 0 ) location += SEATS ; synchronized ( chopsticks ) { while ( chopsticks [ location ] ) chopsticks.wait (); chopsticks [ location ] = true ; System. out. println (" Philosopher " + seat + " picked up chopstick " + location + "."); private void eat () { // done eating, put back chopsticks synchronized ( chopsticks ) { chopsticks [ seat ] = false ; if( seat == 0) chopsticks [ SEATS - 1] = false ; else chopsticks [ seat - 1] = false ; chopsticks.notifyall (); 43

44 Dining Philosophers (Good) import java.util.*; public class DiningPhilosopher2 extends Thread { public static final int SEATS = 5; private static boolean [] chopsticks = new boolean [ SEATS ]; private int seat ; public DiningPhilosopher2 ( int seat ) { this.seat = seat; public static void main ( String args []) { for ( int i = 0; i < SEATS ; i++ ) chopsticks [i] = false ; DiningPhilosopher2 [] philosophers = new DiningPhilosopher2 [ SEATS ]; for ( int i = 0; i < SEATS ; i++ ) { philosophers [i] = new DiningPhilosopher2 ( i ); philosophers[i].start (); try { for ( int i = 0; i < SEATS ; i++ ) philosophers[i].join (); catch ( InterruptedException e ) { e.printstacktrace (); System.out.println ("All philosophers done."); 44

45 public void run () { for ( int i = 0; i < 100; i++ ) { think (); getchopsticks (); eat (); private void think () { Random random = new Random (); try { sleep ( random. nextint (20) + 10 ); catch ( InterruptedException e ) { e. printstacktrace (); private void eat () { // eat rice first synchronized ( chopsticks ) { chopsticks [ seat ] = false ; if( seat == 0) chopsticks [ SEATS - 1] = false ; else chopsticks [ seat - 1] = false ; chopsticks. notifyall (); 45

46 private void getchopsticks () { int location1 = seat ; int location2 ; if( seat == 0 ) location2 = SEATS - 1; else location2 = seat - 1; synchronized ( chopsticks ) { while ( chopsticks [ location1 ] chopsticks [ location2 ] ) { try { chopsticks. wait (); catch ( InterruptedException e ) { e. printstacktrace (); chopsticks [ location1 ] = true ; chopsticks [ location2 ] = true ; System.out.println (" Philosopher " + seat + " picked up chopsticks " + location1 + " and " + location2 + "."); 46

CS18000: Programming I

CS18000: Programming I CS18000: Programming I Synchronization 22 February, 2010 Prof. Chris Clifton Concurrency Example: Banking class ATM { public void withdrawcash(acct a) { Scanner sc = new Scanner(System.in); int amount

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

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

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

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

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing

More information

Synchronization in Concurrent Programming. Amit Gupta

Synchronization in Concurrent Programming. Amit Gupta Synchronization in Concurrent Programming Amit Gupta Announcements Project 1 grades are out on blackboard. Detailed Grade sheets to be distributed after class. Project 2 grades should be out by next Thursday.

More information

Introduction to Java Threads

Introduction to Java Threads Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Objectives Introduce Concept of Critical-Section Problem Hardware and Software Solutions of Critical-Section Problem Concept of Atomic Transaction Operating Systems CS

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

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

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

More information

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

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some

More information

Chapter 6: Synchronization. Operating System Concepts 8 th Edition,

Chapter 6: Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Synchronization, Silberschatz, Galvin and Gagne 2009 Outline Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization

More information

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

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

Dealing with Issues for Interprocess Communication

Dealing with Issues for Interprocess Communication Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed

More information

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

More information

CS180 Review. Recitation Week 15

CS180 Review. Recitation Week 15 CS180 Review Recitation Week 15 Announcement Final exam will be held on Thursday(12/17) 8:00~10:00 AM The coverage is comprehensive Project 5 is graded. Check your score in Blackboard. Classes and Methods

More information

Lesson 6: Process Synchronization

Lesson 6: Process Synchronization Lesson 6: Process Synchronization Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks Semaphores Classic Problems of Synchronization

More information

Concurrent Programming: Threads. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Concurrent Programming: Threads. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Concurrent Programming: Threads CS 180 Sunil Prabhakar Department of Computer Science Purdue University Objectives This week we will get introduced to concurrent programming Creating a new thread of execution

More information

Interprocess Communication By: Kaushik Vaghani

Interprocess Communication By: Kaushik Vaghani Interprocess Communication By: Kaushik Vaghani Background Race Condition: A situation where several processes access and manipulate the same data concurrently and the outcome of execution depends on the

More information

Synchronized Methods of Old Versions of Java

Synchronized Methods of Old Versions of Java Administrivia Assignment #4 is out Due Thursday April 8, 10:00pm no late assignments will be accepted Sign up in labs next week for a demo time In case you hadn t noticed Classes end Thursday April 15

More information

Synchronization Principles

Synchronization Principles Synchronization Principles Gordon College Stephen Brinton The Problem with Concurrency Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms

More information

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6.

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6. Part Three - Process Coordination Chapter 6: Synchronization 6.1 Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure

More information

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems More Synchronization; Concurrency in Java CS 475, Spring 2018 Concurrent & Distributed Systems Review: Semaphores Synchronization tool that provides more sophisticated ways (than Mutex locks) for process

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Chapter 6: Synchronization 6.1 Background 6.2 The Critical-Section Problem 6.3 Peterson s Solution 6.4 Synchronization Hardware 6.5 Mutex Locks 6.6 Semaphores 6.7 Classic

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

More information

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

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition,

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Process Synchronization, Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 4/26/16 Announcements BRING YOUR CORNELL ID TO THE PRELIM. 2 You need it to get in THREADS & CONCURRENCY Prelim 2 is next Tonight BRING YOUR CORNELL ID! A7 is due Thursday. Our Heap.java: on Piazza (A7

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2019 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

Concurrent Programming using Threads

Concurrent Programming using Threads Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object

More information

Faculty of Computers & Information Computer Science Department

Faculty of Computers & Information Computer Science Department Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process

More information

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

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads? Objectives MultiThreading What are Threads? Interrupting threads Thread properties By Võ Văn Hải Faculty of Information Technologies Summer 2012 Threads priorities Synchronization Callables and Futures

More information

Roadmap. Readers-Writers Problem. Readers-Writers Problem. Readers-Writers Problem (Cont.) Dining Philosophers Problem.

Roadmap. Readers-Writers Problem. Readers-Writers Problem. Readers-Writers Problem (Cont.) Dining Philosophers Problem. CSE 421/521 - Operating Systems Fall 2011 Lecture - X Process Synchronization & Deadlocks Roadmap Classic Problems of Synchronization Readers and Writers Problem Dining-Philosophers Problem Sleeping Barber

More information

Synchronization synchronization.

Synchronization synchronization. Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two

More information

CSCD 330 Network Programming

CSCD 330 Network Programming CSCD 330 Network Programming Lecture 12 More Client-Server Programming Winter 2016 Reading: References at end of Lecture 1 Introduction So far, Looked at client-server programs with Java Sockets TCP and

More information

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

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

Process Synchronization

Process Synchronization CS307 Process Synchronization Fan Wu Department of Computer Science and Engineering Shanghai Jiao Tong University Spring 2018 Background Concurrent access to shared data may result in data inconsistency

More information

Process Synchronization

Process Synchronization CSC 4103 - Operating Systems Spring 2007 Lecture - VI Process Synchronization Tevfik Koşar Louisiana State University February 6 th, 2007 1 Roadmap Process Synchronization The Critical-Section Problem

More information

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture) Dept. of Computer Science & Engineering Chentao Wu wuct@cs.sjtu.edu.cn Download lectures ftp://public.sjtu.edu.cn User:

More information

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University Synchronization Design, Spring 2011 Department of Computer Science Synchronization Basic problem: Threads are concurrently accessing shared variables The access should be controlled for predictable result.

More information

Threads Questions Important Questions

Threads Questions Important Questions Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions

More information

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

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

More information

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - XI Deadlocks - II. Louisiana State University

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - XI Deadlocks - II. Louisiana State University CSC 4103 - Operating Systems Fall 2009 Lecture - XI Deadlocks - II Tevfik Ko!ar Louisiana State University September 29 th, 2009 1 Roadmap Classic Problems of Synchronization Bounded Buffer Readers-Writers

More information

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

Roadmap. Bounded-Buffer Problem. Classical Problems of Synchronization. Bounded Buffer 1 Semaphore Soln. Bounded Buffer 1 Semaphore Soln. Tevfik Ko!

Roadmap. Bounded-Buffer Problem. Classical Problems of Synchronization. Bounded Buffer 1 Semaphore Soln. Bounded Buffer 1 Semaphore Soln. Tevfik Ko! CSC 4103 - Operating Systems Fall 2009 Lecture - XI Deadlocks - II Roadmap Classic Problems of Synchronization Bounded Buffer Readers-Writers Dining Philosophers Sleeping Barber Deadlock Prevention Tevfik

More information

Process Synchronization

Process Synchronization Process Synchronization Chapter 6 2015 Prof. Amr El-Kadi Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Spring 1019 L12 Synchronization Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Critical section: shared

More information

Multiple Inheritance. Computer object can be viewed as

Multiple Inheritance. Computer object can be viewed as Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.

More information

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; } Semaphore Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() Can only be accessed via two indivisible (atomic) operations wait (S) { while

More information

CS360 Lecture 12 Multithreading

CS360 Lecture 12 Multithreading CS360 Lecture 12 Multithreading Thursday, March 11, 2004 Reading Multithreading: Chapter 16 Thread States At any time, a thread can be in one of several thread states: - Born: this is the time when the

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

CS 10: Problem solving via Object Oriented Programming Winter 2017

CS 10: Problem solving via Object Oriented Programming Winter 2017 CS 10: Problem solving via Object Oriented Programming Winter 2017 Tim Pierson 260 (255) Sudikoff SynchronizaGon Agenda 1. Threads and interleaving execugon 2. Producer/consumer 3. Deadlock, starvagon

More information

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14 Bruce Char. All rights reserved by the author. Permission is given to students enrolled in CS361 Spring 2000 to reproduce these notes

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

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

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples

More information

Chapter 32 Multithreading and Parallel Programming

Chapter 32 Multithreading and Parallel Programming Chapter 32 Multithreading and Parallel Programming 1 Objectives To get an overview of multithreading ( 32.2). To develop task classes by implementing the Runnable interface ( 32.3). To create threads to

More information

Performance Throughput Utilization of system resources

Performance Throughput Utilization of system resources Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency

More information

Programming Language Concepts: Lecture 11

Programming Language Concepts: Lecture 11 Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]

More information

CHAPTER 6: PROCESS SYNCHRONIZATION

CHAPTER 6: PROCESS SYNCHRONIZATION CHAPTER 6: PROCESS SYNCHRONIZATION The slides do not contain all the information and cannot be treated as a study material for Operating System. Please refer the text book for exams. TOPICS Background

More information

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

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition Module 6: Process Synchronization 6.1 Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

More information

Concurrency in Java Prof. Stephen A. Edwards

Concurrency in Java Prof. Stephen A. Edwards Concurrency in Java Prof. Stephen A. Edwards The Java Language Developed by James Gosling et al. at Sun Microsystems in the early 1990s Originally called Oak, first intended application was as an OS for

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

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

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

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

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

Object Oriented Programming and Design in Java. Session 18 Instructor: Bert Huang

Object Oriented Programming and Design in Java. Session 18 Instructor: Bert Huang Object Oriented Programming and Design in Java Session 18 Instructor: Bert Huang Announcements Homework 4 due Mon. Apr. 19 No multithreading in programming part Final Exam Monday May 10, 9 AM - noon, 173

More information

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

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

Process Coordination

Process Coordination Process Coordination Why is it needed? Processes may need to share data More than one process reading/writing the same data (a shared file, a database record, ) Output of one process being used by another

More information

i219 Software Design Methodology 12. Case study 1 Dining philosopher problem Kazuhiro Ogata (JAIST) Outline of lecture

i219 Software Design Methodology 12. Case study 1 Dining philosopher problem Kazuhiro Ogata (JAIST) Outline of lecture i219 Software Design Methodology 12. Case study 1 Dining philosopher problem Kazuhiro Ogata (JIST) Outline of lecture 2 Dining philosopher problem (DPP) Dining Room in UML & Java Chopstick in UML & Java

More information

Synchronization in Java

Synchronization in Java Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park Synchronization Overview Unsufficient atomicity Data races Locks Deadlock Wait /

More information

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9 CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code? 1 Chapter 8 Threads Question 1: Which one statement below is true concerning the following code? 1. class Hevron extends java.util.vector implements Runnable 2. 3. public void run(int counter) 4. 3. System.out.println("in

More information

Silberschatz and Galvin Chapter 6

Silberschatz and Galvin Chapter 6 Silberschatz and Galvin Chapter 6 Process Synchronization CPSC 410--Richard Furuta 2/26/99 1 Topics discussed Process synchronization Mutual exclusion--hardware Higher-level abstractions Ð Semaphores Ð

More information

THREADS & CONCURRENCY

THREADS & CONCURRENCY 27/04/2018 Sorry for the delay in getting slides for today 2 Another reason for the delay: Yesterday: 63 posts on the course Piazza yesterday. A7: If you received 100 for correctness (perhaps minus a late

More information

COMP346 Winter Tutorial 4 Synchronization Semaphores

COMP346 Winter Tutorial 4 Synchronization Semaphores COMP346 Winter 2015 Tutorial 4 Synchronization Semaphores 1 Topics Synchronization in Details Semaphores Introducing Semaphore.java 2 Synchronization What is it? An act of communication between unrelated

More information

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

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

Only one thread can own a specific monitor

Only one thread can own a specific monitor Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification

More information

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? Why Multicore? What is a Thread? But a fast computer runs hot THREADS AND CONCURRENCY. Concurrency (aka Multitasking) What is a Thread? 2 THREADS AND CONCURRENCY A separate process that can perform a computational task independently and concurrently with other threads Most programs have only one thread GUIs have a separate

More information

Concurrency. Chapter 5

Concurrency. Chapter 5 Concurrency 1 Chapter 5 2 Concurrency Is a fundamental concept in operating system design Processes execute interleaved in time on a single processor Creates the illusion of simultaneous execution Benefits

More information

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

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications CISC 4700 L01 Network & Client-Server Programming Spring 2016 Cowell Chapter 15: Writing Threaded Applications Idea: application does simultaneous activities. Example: web browsers download text and graphics

More information

3C03 Concurrency: Starvation and Deadlocks

3C03 Concurrency: Starvation and Deadlocks 3C03 Concurrency: Starvation and Deadlocks Wolfgang Emmerich 1 Goals Reader/Writer problem Starvation Dining Philosophers Problem Deadlocks Liveness Analysis using LTS 2 1 Reader / Writer Problem Monitors

More information

THREADS AND CONCURRENCY

THREADS AND CONCURRENCY THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on

More information

Process Management And Synchronization

Process Management And Synchronization Process Management And Synchronization In a single processor multiprogramming system the processor switches between the various jobs until to finish the execution of all jobs. These jobs will share the

More information

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

More information

Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues

Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues Concurrency Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues What is program execution? In order to run, a program must be loaded into memory and given an initial state. Code

More information

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

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1 CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms

More information

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018 Deadlock and Monitors CS439: Principles of Computer Systems February 7, 2018 Last Time Terminology Safety and liveness Atomic Instructions, Synchronization, Mutual Exclusion, Critical Sections Synchronization

More information

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

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 9: Readers-Writers and Language Support for Synchronization 9.1.2 Constraints 1. Readers can access database

More information

Module - 4 Multi-Threaded Programming

Module - 4 Multi-Threaded Programming Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is

More information

RACE CONDITIONS AND SYNCHRONIZATION

RACE CONDITIONS AND SYNCHRONIZATION RACE CONDITIONS AND SYNCHRONIZATION Lecture 21 CS2110 Fall 2010 Reminder 2 A race condition arises if two threads try and share some data One updates it and the other reads it, or both update the data

More information

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

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency CS 361 Concurrent programming Dreel University Fall 2004 Lecture 6 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

Last Class: Synchronization Problems!

Last Class: Synchronization Problems! Last Class: Synchronization Problems! Reader Writer Multiple readers, single writer In practice, use read-write locks Dining Philosophers Need to hold multiple resources to perform task Lecture 11, page

More information

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION COMP 346 WINTER 2018 1 Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION REVIEW - MULTITHREADING MODELS 2 Some operating system provide a combined user level thread and Kernel level thread facility.

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information