Race Conditions & Synchronization

Similar documents
Race Conditions & Synchronization

Synchronization. Announcements. Concurrent Programs. Race Conditions. Race Conditions 11/9/17. Purpose of this lecture. A8 released today, Due: 11/21

Synchronization Lecture 23 Fall 2017

Results of prelim 2 on Piazza

Synchronization Lecture 24 Fall 2018

RACE CONDITIONS AND SYNCHRONIZATION

THREADS & CONCURRENCY

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

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

THREADS & CONCURRENCY

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

CS11 Java. Fall Lecture 7

THREADS AND CONCURRENCY

An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation

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

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

Synchronization COMPSCI 386

Chapter 32 Multithreading and Parallel Programming

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

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

Synchronization

Monitors; Software Transactional Memory

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

OS06: Monitors in Java

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Lecture 29: Java s synchronized statement

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

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

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

Stacks and Queues

Threads, Concurrency, and Parallelism

Monitors; Software Transactional Memory

CMSC 330: Organization of Programming Languages

What's wrong with Semaphores?

Synchronization in Concurrent Programming. Amit Gupta

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

Concurrency. Chapter 5

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

Concurrent Programming Benoît Garbinato

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Part IV Other Systems: I Java Threads

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

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Java Threads. Introduction to Java Threads

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

CSE 153 Design of Operating Systems

What is a thread anyway?

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

Last Class: Synchronization

Recap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.

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

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

Chapter 6: Process Synchronization

Programming in Parallel COMP755

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

Lecture Topics. Announcements. Today: Concurrency (Stallings, chapter , 5.7) Next: Exam #1. Self-Study Exercise #5. Project #3 (due 9/28)

Concurrent Programming

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set?

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS

More thread safety and Concurrent collections. Nasser Giacaman CompSci 230: Software Design and Construction

Today: Synchronization. Recap: Synchronization

The New Java Technology Memory Model

CS 351 Design of Large Programs Threads and Concurrency

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

COMP 322: Fundamentals of Parallel Programming

Dr.-Ing. Michael Eichberg

Threads Questions Important Questions

Lecture 8: September 30

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

Exercises and Labs. Part I. Exercises

Principles of Software Construction: Objects, Design and Concurrency. The Perils of Concurrency, Part 2 Can't live with it. Cant live without it.

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Dr.-Ing. Michael Eichberg

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

Lecture 9: Introduction to Monitors

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

6.033 Computer System Engineering

Java Programming Lecture 23

COMP 346 Winter 2019 Programming Assignment 2

Concurrent Programming using Threads

+ Today. Lecture 26: Concurrency 3/31/14. n Reading. n Objectives. n Announcements. n P&C Section 7. n Race conditions.

Homework 12 Due Wednesday, 12/8/10

Threads & Concurrency

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Synchronization. Disclaimer: some slides are adopted from the book authors slides with permission 1

CS 153 Design of Operating Systems Winter 2016

Threads & Concurrency

CS 571 Operating Systems. Midterm Review. Angelos Stavrou, George Mason University

Process Synchronization

Threads Chate Patanothai

CS 159: Parallel Processing

Advances in Programming Languages

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

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

CMSC 330: Organization of Programming Languages

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

Faculty of Computers & Information Computer Science Department

Transcription:

Race Conditions & Synchronization Lecture 25 Spring 2017

Gries office hours 2 A number of students have asked for time to talk over how to study for the prelim. Gries will hold office hours at the times below for this purpose. Also, read basiclearningmethods.pdf in the pinned Piazza note Supplementary material. Tues. (today) 1-4PM. Wed. (tomorrow) 10-noon

How end of course works 3 A8 due last day of classes: Wednesday, 10 May Firm deadline. Nothing after that. We grade A8 as quickly as possible, then figure out tentative course letter grades. Make them available on the CMS. You complete a CMS assignment: Do you accept grade or take final. Taking the final can lower as well as raise your grade. Final is Sunday, 21 May, at 2PM.

Purpose of this lecture 4 Show you Java constructs for eliminating race conditions, allowing threads to access a data structure in a safe way but allowing as much concurrency as possible. This requires (1) The locking of an object so that others cannot access it, called synchronization. (2) Use of other Java methods: Wait() and NotifyAll() As an example, throughout, we use a bounded buffer.

Recap 5 A race condition arises if two threads try to read and write the same data Might see the data in the middle of an update in a inconsistent stare A race condition : correctness depends on the update racing to completion without the reader managing to glimpse the in-progress update Synchronization (also known as mutual exclusion) solves this

6 Important example: bounded buffer A baker produces breads and puts them on the shelf, like a queue. Customers take them off the shelf. Threads A: produce loaves of bread and put them in the queue Threads B: consume loaves by taking them off the queue This is the producer/consumer model, using a bounded buffer, the shelf (which can contain at most 20 (say) loaves of bread). producer shelf consumer

Array implementation of a queue of max size 6 7 Array b[0..5] b 0 1 2 3 4 5 b.length 5 3 6 2 4 push values 5 3 6 2 4 For later purposes, we show how to implement a bounded queue one with some maximum size in an array. A neat little implementation! We give you code for it on course website.

Array implementation of a queue of max size 6 8 Array b[0..5] b 0 1 2 3 4 5 b.length 5 3 6 2 4 pushed values 5 3 6 2 4 Now, pop, pop, pop

Array implementation of a queue of max size 6 9 Array b[0..5] b 0 1 2 3 4 5 b.length 3 5 2 4 1 Values wrap around!! push values 5 3 6 2 4 pop, pop, pop push value 1 3 5

10 Array implementation of a queue b h 0 1 2 3 4 5 b.length 3 5 2 4 1 Values wrap around!! Fields and the class invariant int[] b; // The n elements of the queue are in int n; // b[h], b[(h+1) % b.length],... b[(h+n-1) % b.length] int h; // 0 <= h < b.length Insert 7 (assuming there s space) b[(h+n)% b.length]= 5; n= n+1; Pop (assuming not empty) value= b[h]; h= (h+1) % b.length

Java Synchronization (Locking) 11 public AQ<String> aq= new AQ<String>(); public void dosomethingto-aq() { code to change aq We need a way to prohibit other threads from using AQ aq while the code to change aq is being executed. For this purpose, we use Java keyword synchronize

Java Synchronization (Locking) 12 private AQ<String> aq= new AQ<String>(); public void dosomethingto-aq() { synchronize { code to change aq synchronized block While this method is executing the synchronized block, object aq is locked. No other thread can obtain the lock. Only one thread can own the lock at a time

Java Synchronization (Locking) 13 You can lock on any object, including this public void dosomething() { synchronized (this) {... Why do this? Suppose method dosomething is within an object of class ArrayQueue, and we want to prohibit other methods within ArrayQueue from being executed. Below is syntactic sugar for the stuff below. They mean the same thing. public synchronized void dosomething() {...

Bounded Buffer 14 /** An instance maintains a bounded buffer of limited size */ class BoundedBuffer { ArrayQueue aq; // bounded buffer is implemented in aq /** Constructor: empty bounded buffer of max size n*/ public BoundedBuffer(int n) { aq= new ArrayQueue(n); Separation of concerns: 1. How do you implement a queue in an array? 2. How do you implement a bounded buffer, which allows producers to add to it and consumers to take things from it, all in parallel?

Bounded Buffer 15 /** An instance maintains a bounded buffer of limited size */ class BoundedBuffer { ArrayQueue aq; // bounded buffer is implemented in aq /** Put v into the bounded buffer.*/ public synchronized void produce(integer v) { aq.put(v); We know more code will be put in method produce, and we want to be sure that no other method in this Bounded Buffer object can do anything with this object until method produce is finished. So stick in a synchronize keyword.

Bounded Buffer: producer 16 /** An instance maintains a bounded buffer of limited size */ class BoundedBuffer { ArrayQueue aq; // bounded buffer is implemented in aq /** Put v into the bounded buffer.*/ public synchronized void produce(integer v) { aq.put(v); What happens of aq is full? We have to wait until it becomes non-full until there is a place to put v. Somebody has to buy a loaf of bread before we can put more bread on the shelf. We use a while-loop to wait, and we also need to give p the lock so some other thread can buy (consume) a loaf of bread.

17 Bounded Buffer: producer /** An instance maintains a bounded buffer of limited size */ class BoundedBuffer { ArrayQueue aq; // bounded buffer implemented in aq /** Put v into the bounded buffer.*/ public synchronized void produce(integer v) { while (aq.isfull()) try { wait(); catch (InterruptedExecution e) { aq.put(v); more to come wait(): put on a list of waiting threads, give up lock so another thread can have it Need a while-loop to wait. An if-statement will no work. If the wait is interrupted for some reason, just continue

18 Bounded Buffer: producer /** An instance maintains a bounded buffer of limited size */ class BoundedBuffer { ArrayQueue aq; // bounded buffer implemented in aq /** Put v into the bounded buffer.*/ public synchronized void produce(integer v) { while (aq.isfull()) try { wait(); catch (InterruptedExecution e) { aq.put(v); notifyall(); Another thread may be waiting because the buffer is empty ---no more bread. Have to notify all waiting threads that it is not empty The consumer method consume is similar. Let s look at code.

Things to notice 19 Use a while loop because we can t predict exactly which thread will wake up next wait() waits on the same object that is used for synchronizing (in our example, this, which is this instance of the bounded buffer) Method notify() wakes up one waiting thread, notifyall() wakes all of them up

About wait(), wait(n), notify(), notifyall() 20 A thread that holds a lock on object OB and is executing in its synchronized code can make (at least) these calls. 1. wait(); It is put into set 2. Another thread from set 1 gets the lock. 2. wait(n); It is put into set 2 and stays there for at least n millisecs. Another thread from set 1 gets the lock. 3. notify(); Move one possible thread from set 2 to set 1. 4. notifyall(); Move all threads from set 2 to set 1. Two sets: 1. Runnable threads: Threads waiting to get the OB lock. 2. Waiting threads: Threads that called wait and are waiting to be notified

About wait(), wait(n), notify(), notifyall() 21 A thread that executing in its synchronized code can make (at least) these calls. 1. wait(); It is put into set 2. Another thread from set 1 gets the lock. 3. notify(); Move one possible thread from set 2 to set 1. 4. notifyall(); Move all threads from set 2 to set 1. Notify() a lot less expensive than notifyall(). Why not use it all the time? Because the wrong thread may be notified, giving deadlock Two sets: 1. Runnable threads: Threads waiting to get the OB lock. 2. Waiting threads: Threads that called wait and are waiting to be notified

Should one use notify() or notifyall() 22 But suppose there are two kinds of bread on the shelf and one still picks the head of the queue, if it s the right kind of bread. Using notify() can lead to a situation in which no one can make progress. We illustrate with a project in Eclipse, which is on the course website. notifyall() always works; you need to write documentation if you optimize by using notify()

23 WHY use of notify() may hang. Two sets: 1. Runnable: Work with a bounded buffer of length 1. 1. Consumer W gets lock, wants White bread, threads finds buffer empty, and wait()s: is put in set 2. waiting to 2. Consumer R gets lock, wants Rye bread, get lock. finds buffer empty, wait()s: is put in set 2. 2. Waiting: 3. Producer gets lock, puts Rye in the buffer, does notify(), gives up lock. threads 4. The notify() causes one waiting thread to be waiting to moved from set 2 to set 1. Choose W. be notified 5. No one has lock, so one Runnable thread, W, is given lock. W wants white, not rye, so wait()s: is put in set 2. 6. Producer gets lock, finds buffer full, wait()s: is put in set 2. All 3 threads are waiting in set 2. Nothing more happens.

Using Concurrent Collections... 24 Java has a bunch of classes to make synchronization easier. It has synchronized versions of some of the Collections classes It has an Atomic counter.

From spec for HashSet 25 this implementation is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the set. If no such object exists, the set should be "wrapped" using method Collections.synchronizedSet This is best done at creation time, to prevent accidental unsynchronized access to the set: Set s = Collections.synchronizedSet(new HashSet(...));

Using Concurrent Collections... 26 import java.util.concurrent.atomic.*; public class Counter { private static AtomicInteger counter; public Counter() { counter= new AtomicInteger(0); public static int getcount() { return counter.getandincrement();

Summary 27 Use of multiple processes and multiple threads within each process can exploit concurrency n may be real (multicore) or virtual (an illusion) Be careful when using threads: n synchronize shared memory to avoid race conditions n avoid deadlock Even with proper locking concurrent programs can have other problems such as livelock Serious treatment of concurrency is a complex topic (covered in more detail in cs3410 and cs4410) Nice tutorial at http://docs.oracle.com/javase/tutorial/essential/concurrency/ index.html