1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 6: Process Synchronization
Background Concurrent access to shared data can lead to inconsistencies Maintaining data consistency among cooperating processes is critical What is wrong.
5.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 5: CPU Scheduling.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Mutual Exclusion.
Multithreaded Programs in Java. Tasks and Threads A task is an abstraction of a series of steps – Might be done in a separate thread – Java libraries.
Concurrency 101 Shared state. Part 1: General Concepts 2.
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
1 Java threads: synchronization. 2 Thread states 1.New: created with the new operator (not yet started) 2.Runnable: either running or ready to run 3.Blocked:
Multi-Threading Dr. M. Khamis. Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
02/23/2004CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 What is the “volatile” Keyword? You can skip locking (thread synchronization) in some cases by using the volatile variables. –No locking/unlocking =
1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0.
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
02/19/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
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.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CSE 219 Computer Science III Multithreaded Issues.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
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.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Java Thread and Memory Model
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
CMSC 330: Organization of Programming Languages Threads.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
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.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
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.
Synchronization Questions answered in this lecture: Why is synchronization necessary? What are race conditions, critical sections, and atomic operations?
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Multithreading / Concurrency
Multi Threading.
COEN346 Tutorial Monitor Objects.
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Monitors Chapter 7.
Thread Synchronization
Monitors Chapter 7.
Monitors Chapter 7.
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
CSE 451: Operating Systems Autumn 2005 Lecture 7 Synchronization
CSE 451: Operating Systems Winter 2003 Lecture 7 Synchronization
CSE 153 Design of Operating Systems Winter 19
CSE 153 Design of Operating Systems Winter 2019
CS333 Intro to Operating Systems
Threads and Multithreading
Process/Thread Synchronization (Part 2)
Software Engineering and Architecture
Presentation transcript:

1 Thread II Slides courtesy of Dr. Nilanjan Banerjee

2 Race condition explained… What is the shared object in our example? the Bank object?? Accessing shared objects is also termed as accessing “critical sections” of data Lets look at a statement in the critical section. account[to] += amount;

3 Race condition explained.. Lets decompose the previous statement into assembly and see what it constitutes.. Load accounts[to] to some register Add amount to that register Copy back the result into the memory location The problem is that the above three statements are not atomic (Atomic operation is something that cannot be preempted) Lets see what can potentially happen when two threads simultaneously access this statement…

4 Race condition explained… Load X R1 Add Y Z R1 Store Y in Mem Thread 1 executes the first two statements and is preempted… Thread 2 executes all the three statements Thread 1 returns and executes the third statement What has happened here?

5 Intuitively how would you solve this problem… First solution: allow only one thread to access the “critical section” or “shared object” at one time!!!! Easiest way of doing this is using locks… java.util.concurrent provides the Lock interface and ReentrantLock implementation Lock myLock = new ReentrantLock(); myLock.lock(); //acquire a lock.. try { critical section….. } catch(Exception e) {} myLock.unlock() //give up the lock

6 Properties of locks… Only one Thread can acquire a lock at one time Suppose one Thread acquires the lock Second Thread tries to acquire it Second Thread blocks till first Thread releases the lock Make sure every lock is accompanied by an unlock statement Else things will block forever  Reentrant means the same Thread can acquire the lock multiple times In our example every Bank object has a separate lock… For different Bank objects the locks are completely different.. They do not collide…

7 Condition objects! Lets refine our Bank example Add a condition that you can transfer data only if there is sufficient balance Unsynchronized way of doing it if(accounts[from] > amount) { carry out the transfer…} Problem If(accounts[from] > amount) { Thread preempted… Some other thread removes the money from the account Thread scheduled again.. //now the operation is just WRONG!!! }

8 Lets see if we can use locking to solve this mylock.lock(); while(account[from] < amount){ Thread.sleep(100); } //do the transfer… mylock.unlock(); What is the problem here? Only one Thread can acquire the lock.. This might lead to a deadlock…

9 Java’s conditional variables Java provides Conditional variables with every Lock How do you use it:: Using a conditional (you can declare as many as you want) private Lock myLock = new ReentrantLock(); public Bank() { //constructor private Condition sufficientFunds = myLock.newCondition();} myLock.lock(); while(accounts[from] < amount) { sufficientFunds.await(); // } //Transfer funds.. sufficientFunds.signalAll(); myLock.unlock();

10 Lets take a closer look at the await() and signalAll() sufficientFunds.await() It pulls the Thread out of the run queue and places it in a condition queue (specific to that particular condition) Releases the lock that the thread was holding Consequently other Threads that are blocked on that lock can get the CPU!!! sufficientFunds.signalAll() Signals all the Threads that are waiting on that particular condition Indication that condition (sufficientFunds) in our case in now satisfied… The Thread can be scheduled if it has the lock.

11 Difference between conditional wait and waiting on a lock Condition Queue 1 Condition Queue 2 CPU Blocked on lock Wait on a lock unlock Run Condition.await() Condition.signalAll()

12 Summary of locking and conditional A lock protects a section of code, allowing only one thread to access the critical section at one time A lock manages threads that are trying to enter this “protected” code segment A lock can have more than one conditional objects associated with it Each conditional object manages threads that have entered a protected code section but cannot proceed due to a “condition”.

13 The synchronized keyword! Locks and Conditions provide you with fine-grained synchronization However there is an easier way of synchronizing object if you are ready to sacrifice some of the flexibility The Java language provides a keyword “synchronized” that can be used to make a method thread-safe Every Java object has an intrinsic lock Calling a method synchronized uses that intrinsic lock Lets take an example //In Bank.java public synchronized void transfer() { … method body…. }..

14 Take a close look at the synchronized method public synchronized void transfer() { ….method body….. } public void transfer() { this.intrinsicLock.lock(); // acquire the intrinsic lock ….method body….. this.intrinsicLock.unlock() //release the instrinsic lock } Equivalent to the following

15 Conditionals for the intrinsic lock public synchronized void transfer() { while (accounts[from] < amount) wait(); accounts[from] -= amount; accounts[to] += amount; notifyAll(); } public void transfer() { this.intrinsicLock.lock(); // acquire the intrinsic lock While(accounts[from] < amount) this.intrinsicLock.getCondition().await();.. Do stuff… This.intrinsicLock.getCondition().signalAll() this.intrinsicLock.unlock() //release the instrinsic lock } Equivalent to the following Every intrinsic lock is associated with only ONE intrinsic conditional

16 Limitations of using synchronized… One lock for the entire object One conditional that you can use… Pros: very clean code.. Just need to append the method name with the synchronized keyword

17 Concept of a monitor One big problem with locks is it is not a very object-oriented concept For years developers of thought of providing synchronization without explicit locks That is where the concept of a monitor comes into being Monitor is a class that has only private elements Every object has an implicit lock that is acquired when the a method is called and released when the method exits Obj.method() – first acquire the lock and on returning release the lock You can have as many conditionals as possible How does Java’s synchronization mechanism differ from monitors?

18 Use of volatile In some cases using locks might be too expensive public synchronized boolean isDone() { return done;} public synchronized void setDone() { done = true;} private boolean done; public boolean isDone() { return done;} public void setDone() { done = true;} private volatile boolean done;

19 There are some concurrent classes Java.util.concurrent.* ConcurrentHashMap ConcurrentSkipList ConcurrentSkipListSet

20 Deadlock situation We have already seen one condition where threads might just be deadlocked due to use of locking and using await(). Another situation due to multiple locks. Thread 1Thread Lock1.lock() Lock2.lock() Lock2.lock() Lock1.lock() ….do something… Lock2.unlock() Lock1.unlock() Lock1.unlock() Lock2.unlock()