Synchronization Lecture 24 Fall 2018

Similar documents
Results of prelim 2 on Piazza

Synchronization Lecture 23 Fall 2017

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

Race Conditions & Synchronization

Race Conditions & Synchronization

RACE CONDITIONS AND SYNCHRONIZATION

THREADS & CONCURRENCY

THREADS & CONCURRENCY

THREADS AND CONCURRENCY

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

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

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

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

Atomicity CS 2110 Fall 2017

Synchronization COMPSCI 386

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

Synchronization in Concurrent Programming. Amit Gupta

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430

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

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

Threads, Concurrency, and Parallelism

Dealing with Issues for Interprocess Communication

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

Lecture 8: September 30

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

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

COMP346 Winter Tutorial 4 Synchronization Semaphores

CS11 Java. Fall Lecture 7

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

Introduction to OS Synchronization MOS 2.3

CS370 Operating Systems

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

Monitors; Software Transactional Memory

Last Class: Synchronization

What's wrong with Semaphores?

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

Concurrency. Chapter 5

Monitors; Software Transactional Memory

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall

Advances in Programming Languages

OS Process Synchronization!

Synchronization I. Jo, Heeseung

CS 10: Problem solving via Object Oriented Programming Winter 2017

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

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

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

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ!

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

Midterm Exam Amy Murphy 19 March 2003

Chapter 32 Multithreading and Parallel Programming

CS 31: Intro to Systems Misc. Threading. Kevin Webb Swarthmore College December 6, 2018

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

Concurrency: Mutual Exclusion (Locks)

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

Part IV Other Systems: I Java Threads

CSE 153 Design of Operating Systems

The New Java Technology Memory Model

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

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

Today: Synchronization. Recap: Synchronization

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

Interprocess Communication By: Kaushik Vaghani

CSE 410 Final Exam 6/09/09. Suppose we have a memory and a direct-mapped cache with the following characteristics.

University of Waterloo Midterm Examination Model Solution CS350 Operating Systems

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

Concurrent Programming

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

Suggested Solutions (Midterm Exam October 27, 2005)

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

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

Process/Thread Synchronization

PROCESS SYNCHRONIZATION

Multiple Inheritance. Computer object can be viewed as

Programming in Parallel COMP755

Dr. D. M. Akbar Hussain DE5 Department of Electronic Systems

Concurrency: a crash course

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

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

Background. The Critical-Section Problem Synchronisation Hardware Inefficient Spinning Semaphores Semaphore Examples Scheduling.

Lecture 29: Java s synchronized statement

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

5. Synchronization. Operating System Concepts with Java 8th Edition Silberschatz, Galvin and Gagn

Threads Questions Important Questions

The concept of concurrency is fundamental to all these areas.

CS 153 Design of Operating Systems Winter 2016

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

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

Concurrency, Thread. Dongkun Shin, SKKU

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CS370 Operating Systems

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

Last Class: Synchronization Problems. Need to hold multiple resources to perform task. CS377: Operating Systems. Real-world Examples

Lecture 5 Threads and Pthreads II

CSCD 330 Network Programming

Page 1. Goals for Today" Atomic Read-Modify-Write instructions" Examples of Read-Modify-Write "

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

Chapter 6: Process Synchronization

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

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

CHAPTER 6: PROCESS SYNCHRONIZATION

Transcription:

Synchronization Lecture 24 Fall 2018

Prelim 2 tonight! The room assignments are on the course website, page Exams. Check it carefully! Come on time! Bring you Cornell id card! No lunch with gries this morning. Too much going on. Will reschedule for after Thanksgiving.

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. Last time: Learned about 1. Race conditions 2. Deadlock 3. How to create a thread in Java.

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 two new Java methods: wait() and notifyall() As an example, throughout, we use a bounded buffer. Look at JavaHyperText, entry Thread!!!!!!!

An Example: bounded buffer 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 buffer 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 8 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 9 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

10 ArrayQueue b h 0 1 2 3 4 5 b.length 3 5 2 4 1 Values wrap around!! int[] b; // 0 <= h < b.length. The queue contains the int h; // n elements b[h], b[h+1], b[h+2], int n; // b[h+n-1] (all indices mod b.length) /** 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 11 /** 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() { return aq.isempty()? null : aq.get();

Bounded Buffer 12 /** 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) ; Problems 1. Chef doesn t easily know whether bread was added. 2. Suppose (a) First chef finds it not full. (b) Another chef butts in and adds a bread (c) First chef tries to add and can t because it s full. Need a way to prevent this

Synchronized block a.k.a. locks or mutual exclusion synchronized (object { Execution of the synchronized block: 1. Acquire the object, so that no other thread can acquire it and use it. 2. Execute the block. 3. Release the object, so that other threads can acquire it. 1. Might have to wait if other thread has acquired object. 2. While this thread is executing the synchronized block, The object is locked. No other thread can obtain the lock.

Bounded Buffer 14 /** 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) ; After finding aq not full, but before putting v, another chef might beat you to it and fill up buffer aq!

Use of synchronized 15 Key is hanging the outhouse. synchronized (object) { code The object is the outhouse. The code is the person, waiting to get into the object. If the key is on the door, the code takes it, goes in, locks the door, executes, opens the door, comes out, and hangs the key up. Anyone can grab the key, go inside, and lock the door. They have the key. When they come out, they lock the door and hang the key by the front door. Anyone (only one) person can then grab the key, go inside, lock the door. That s what synchronized implements!

Synchronized block 16 /** 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) { synchronized (aq) { if (!aq.isfull()) { aq.put(v) ;

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. BB@10 BB@10 BB aq produce() { consume() {

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 wrapping the entire method implementation in a synchronized(this) block

Bounded buffer 19 /** 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 Consume to wait v until from it becomes the bounded non-full buffer.*/ until there is public a place synchronized to put v. E consume() { Somebody return has aq.isempty() to buy a loaf of? bread null : before aq.get(); we can put more bread on the shelf.

Two lists for a synchronized object 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 Method wait() is defined in Object

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

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

notify() and notifyall() 23 /** 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()...

24 WHY use of notify() may hang. Two sets: Work with a bounded buffer of length 1. 1. lock: 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. wait: 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() 25 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()

Eclipse Example 26 Producer: produce random ints Consumer 1: even ints Consumer 2: odd ints Dropbox: 1-element bounded buffer Locklist Threads wanting the Dropbox Waitlist Threads who had Dropbox and waited

Word of warning with synchronized 27 BUT: You leave the back door open and tell your friends to go in whenever they want Threads that don t synchronize can get in. Dangerous but useful to increase efficiency. Key is hanging by front door. Anyone can grab the key, go inside, and lock the door. They have the key. When they come out, they lock the door and hang the key by the front door. Anyone (only one) person can then grab the key, go inside, lock the door. That s what synchronized implements!

Using Concurrent Collections... 28 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 29 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... 31 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();

32 Fancier forms of locking Java. synchronized is the core mechanism But. Java has a class Semaphore. It can be used to allow a limited number of threads (or kinds of threads) to work at the same time. Acquire the semaphore, release the semaphore Semaphore: a kind of synchronized counter (invented by Dijkstra in 1962-63, THE multiprogramming system) The Windows and Linux and Apple O/S have kernel locking features, like file locking Python: acquire a lock, release the lock. Has semaphores

Summary 33 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