Synchronization Lecture 23 Fall 2017

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

Synchronization Lecture 24 Fall 2018

Results of prelim 2 on Piazza

Race Conditions & Synchronization

Race Conditions & Synchronization

RACE CONDITIONS AND SYNCHRONIZATION

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

THREADS & CONCURRENCY

Threads, Concurrency, and Parallelism

THREADS & CONCURRENCY

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

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

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

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

CS11 Java. Fall Lecture 7

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

THREADS AND CONCURRENCY

Monitors; Software Transactional Memory

CS180 Review. Recitation Week 15

Atomicity CS 2110 Fall 2017

Monitors; Software Transactional Memory

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

Synchronization in Concurrent Programming. Amit Gupta

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

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

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

Programming in Parallel COMP755

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

Lecture 29: Java s synchronized statement

Chapter 32 Multithreading and Parallel Programming

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

Concurrent Programming

The New Java Technology Memory Model

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

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

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

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

Lecture 21: Transactional Memory. Topics: consistency model recap, introduction to transactional memory

Part IV Other Systems: I Java Threads

CS370 Operating Systems

Synchronization COMPSCI 386

Threads and Too Much Milk! CS439: Principles of Computer Systems January 31, 2018

Threads and Too Much Milk! CS439: Principles of Computer Systems February 6, 2019

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

What is a thread anyway?

Lecture 8: September 30

Concurrency: State Models & Design Patterns

CS 153 Design of Operating Systems Winter 2016

What's wrong with Semaphores?

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

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

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

Concurrency. Chapter 5

Dealing with Issues for Interprocess Communication

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

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

Producing Production Quality Software. Lecture 12: Concurrent and Distributed Programming Prof. Arthur P. Goldberg Fall, 2004

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

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

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

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

Advances in Programming Languages

Introduction to OS Synchronization MOS 2.3

CMSC 330: Organization of Programming Languages

Program Graph. Lecture 25: Parallelism & Concurrency. Performance. What does it mean?

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

CS5460: Operating Systems

CS 450 Exam 2 Mon. 4/11/2016

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

COMP346 Winter Tutorial 4 Synchronization Semaphores

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey

The Java Memory Model

MS Windows Concurrency Mechanisms Prepared By SUFIAN MUSSQAA AL-MAJMAIE

Mutual Exclusion and Synchronization

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

Synchronization in Java

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

Synchronization

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Introduction to Java Threads

3/25/14. Lecture 25: Concurrency. + Today. n Reading. n P&C Section 6. n Objectives. n Concurrency

CSE Traditional Operating Systems deal with typical system software designed to be:

Java Threads. Introduction to Java Threads

CSE332: Data Abstractions Lecture 25: Deadlocks and Additional Concurrency Issues. Tyler Robison Summer 2010

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

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

Advanced MEIC. (Lesson #18)

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

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

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

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

Synchronization I. Jo, Heeseung

Fine-grained synchronization & lock-free data structures

Threads and Parallelism in Java

Threads Questions Important Questions

Multiple Inheritance. Computer object can be viewed as

Today: Synchronization. Recap: Synchronization

Transcription:

Synchronization Lecture 23 Fall 2017

Announcements A8 released today, Due: 11/21 Late deadline is after Thanksgiving You can use your A6/A7 solutions or ours A7 correctness scores have been posted Next week's recitation will focus on A8 Prelim 2 is in one week Deadline for conflicts is today Review session on Sunday 11/14

Concurrent Programs A thread or thread of execution is a sequential stream of computational work. Concurrency is about controlling access by multiple threads to shared resources.

Race Conditions Thread 1 Thread 2 Initially, i = 0 tmp = load i; Load 0 from memory Load 0 from memory tmp = load i; tmp = tmp + 1; store tmp to i; Store 1 to memory time Store 1 to memory Finally, i = 1 tmp = tmp + 1; store tmp to i;

Race Conditions A race condition is a situation in which the result of executing two or more processes in parallel can depend on the relative timing of the execution of the processes. A race condition can arises if two threads try to read and write the same data. Often occurs if a thread might see the data in the middle of an update (in a "inconsistent stare ) Can lead to subtle and hard-to-fix bugs Solved by synchronization

Purpose of this lecture 6 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.

An Example: Bounded Buffers finite capacity (e.g. 20 loaves) implemented as a queue Threads A: produce loaves of bread and put them in the queue Threads B: consume loaves by taking them off the queue

An Example: Bounded Buffers finite capacity (e.g. 20 loaves) implemented as a queue 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? Threads A: produce loaves of bread and put them in the queue Threads B: consume loaves by taking them off the queue

ArrayQueue Array b[0..5] b 0 1 2 3 4 5 b.length 5 3 6 2 4 put values 5 3 6 2 4 into queue

ArrayQueue 10 Array b[0..5] b 0 1 2 3 4 5 b.length 5 3 6 2 4 put values 5 3 6 2 4 into queue get, get, get

ArrayQueue 11 Array b[0..5] b 0 1 2 3 4 5 b.length 3 5 2 4 1 Values wrap around!! put values 5 3 6 2 4 into queue get, get, get put values 1 3 5

12 ArrayQueue b h 0 1 2 3 4 5 b.length 3 5 2 4 1 Values wrap around!! int[] b; // The array elements of the queue are in int h; // location of head, 0 <= h < b.length int n; // number of elements currently in queue /** Pre: there is space */ public void put(int v){ b[(h+n) % b.length]= v; n= n+1; /** Pre: not empty */ public int get(){ int v= b[h]; h= (h+1) % b.length n= n- 1; return v;

Bounded Buffer 13 /** An instance maintains a bounded buffer of fixed size */ class BoundedBuffer<E> { ArrayQueue<E> aq; /** Put v into the bounded buffer.*/ public void produce(e v) { if(!aq.isfull()){ aq.put(v) ; /** Consume v from the bounded buffer.*/ public E consume() { aq.isempty()? return null : return aq.get();

Synchronized Blocks a.k.a. locks or mutual exclusion synchronized (q) { if (!q.isempty()) { q.remove(); At most one consumer thread can be trying to remove something from the queue at a time. While this method is executing the synchronized block, object aq is locked. No other thread can obtain the lock.

Synchronized Blocks public void produce(e v) { synchronized(aq){ synchronized(this){ if(!aq.isfull()){ aq.put(v); You can synchronize (lock) any object, including this.

Synchronized Methods public void produce(e v) { synchronized(this){ if(!aq.isfull()){ aq.put(v); You can synchronize (lock) any object, including this. public synchronized void produce(e v) { if(!aq.isfull()){ aq.put(v); Or you can synchronize methods This is the same as wraping the entire method implementation in a synchronized(this) block

Bounded Buffer 17 /** An instance maintains a bounded buffer of fixed size */ class BoundedBuffer<E> { ArrayQueue<E> aq; What happens of aq is full? /** Put v into the bounded buffer.*/ public synchronized void produce(e v) { if(!aq.isfull()){ aq.put(v); We want 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. /** Consume v from the bounded buffer.*/ public synchronized E consume() { aq.isempty()? return null : return aq.get();

Wait() For every synchronized object sobj, Java maintains: 1. locklist: a list of threads that are waiting to obtain the lock on sobj 2. waitlist: a list of threads that had the lock but executed wait() e.g., because they couldn't proceed wait() is a method defined in Object

Wait() 19 /** An instance maintains a bounded buffer of fixed size */ class BoundedBuffer<E> { ArrayQueue<E> aq; /** Put v into the bounded buffer.*/ public synchronized void produce(e v) { while(aq.isfull()){ try { wait(); catch(interruptedexception e){... aq.put(v); notifyall() need while loop (not if statement) to prevent race conditions puts thread on the wait list threads can be interrupted if this happens just continue

notify() and notifyall() notify() and notifyall() are methods defined in Object notify() moves one thread from the waitlist to the locklist Note: which thread is moved is arbitrary notifyall() moves all the threads on the waitlist to the locklist

notify() and notifyall() 21 /** An instance maintains a bounded buffer of fixed size */ class BoundedBuffer<E> { ArrayQueue<E> aq; /** Put v into the bounded buffer.*/ public synchronized void produce(e v) { while(aq.isfull()){ try { wait(); catch(interruptedexception e){ aq.put(v); notifyall()...

22 WHY use of notify() may hang. Two sets: Work with a bounded buffer of length 1. 1. Runnable: 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. 3. Producer gets lock, puts Rye in the buffer, 2. Waiting: 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.

Should one use notify() or notifyall() 23 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. notifyall() always works; you need to write documentation if you optimize by using notify()

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(...));

Race Conditions Thread 1 Thread 2 Initially, i = 0 tmp = load i; Load 0 from memory Load 0 from memory tmp = load i; tmp = tmp + 1; store tmp to i; Store 1 to memory time Store 1 to memory Finally, i = 1 tmp = tmp + 1; store tmp to i;

Using Concurrent Collections... 27 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 28 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