CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

Similar documents
Programmazione di sistemi multicore

CSE 332: Data Structures & Parallelism Lecture 18: Race Conditions & Deadlock. Ruth Anderson Autumn 2017

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

CSE332: Data Abstractions Lecture 23: Data Races and Memory Reordering Deadlock Readers/Writer Locks Condition Variables. Dan Grossman Spring 2012

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

CSE 332: Data Abstractions Lecture 22: Data Races and Memory Reordering Deadlock Readers/Writer Locks Condition Variables. Ruth Anderson Spring 2014

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 5 Programming with Locks and Critical Sections

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

THE FINAL EXAM MORE ON RACE CONDITIONS. Specific Topics. The Final. Book, Calculator, and Notes

Races. Example. A race condi-on occurs when the computa-on result depends on scheduling (how threads are interleaved)

CSE 332 Data Abstractions: Data Races and Memory, Reordering, Deadlock, Readers/Writer Locks, and Condition Variables (oh my!) Kate Deibel Summer 2012

Programmazione di sistemi multicore

CSE332: Data Abstractions Lecture 19: Mutual Exclusion and Locking

A Sophomoric Introduction to Shared-Memory Parallelism and Concurrency Lecture 4 Shared-Memory Concurrency & Mutual Exclusion

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019

What is the problem?

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

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

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

Thread-unsafe code. Synchronized blocks

Dealing with Issues for Interprocess Communication

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

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

SFDV3006 Concurrent Programming

10/17/ Gribble, Lazowska, Levy, Zahorjan 2. 10/17/ Gribble, Lazowska, Levy, Zahorjan 4

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

Synchronization I. Jo, Heeseung

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

Operating Systems. Synchronization

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

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

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

CSE 374 Programming Concepts & Tools

Advanced Threads & Monitor-Style Programming 1/24

Synchronization I. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Processor speed. Concurrency Structure and Interpretation of Computer Programs. Multiple processors. Processor speed. Mike Phillips <mpp>

CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing

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

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

3C03 Concurrency: Starvation and Deadlocks

Synchronization COMPSCI 386

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

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

Parallel Code Smells: A Top 10 List

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

Chapter 6: Process Synchronization

Interprocess Communication By: Kaushik Vaghani

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

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Process Synchronization

Topics in Parallel and Distributed Computing: Introducing Concurrency in Undergraduate Courses 1,2

Synchronization in Concurrent Programming. Amit Gupta

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

Process Synchronization

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

CMSC 132: Object-Oriented Programming II

Midterm #1. CMSC 433: Programming Language Technologies and Paradigms. October 14, 2013

Only one thread can own a specific monitor

Threads Synchronization

Readers/Writers Problem. Readers/Writers: Scenario 1. Readers/Writers Problem. Today: Synchronization for Readers/Writers Problem

A house of cards? Advanced Synchronization and Deadlock. Contra Threads: Events. Contra Threads: Events

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

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

CSE 332 Winter 2018 Final Exam (closed book, closed notes, no calculators)

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

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

Sec$on 6: Mutual Exclusion. Michelle Ku5el

Chapter 6: Process Synchronization

Operating Systems: (Tue)

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

Semaphores. Mutual Exclusion. Inference Rules. Fairness: V may release a waiting process. Weakly fair, Strongly fair, or FIFO

Process Coordination

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (II)

CSCD 330 Network Programming

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

Chapter 7: Process Synchronization!

CSCD 330 Network Programming

Synchronization Basic Problem:

Operating Systems: William Stallings. Starvation. Patricia Roy Manatee Community College, Venice, FL 2008, Prentice Hall

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Midterm Exam #2 Solutions October 25, 2016 CS162 Operating Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

G52CON: Concepts of Concurrency

The University of Texas at Arlington

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

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

The University of Texas at Arlington

Introduction to Data Management CSE 344

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

! Why is synchronization needed? ! Synchronization Language/Definitions: ! How are locks implemented? Maria Hybinette, UGA

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019

Lecture 10: Multi-Object Synchronization

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

McRT-STM: A High Performance Software Transactional Memory System for a Multi- Core Runtime

Last Class: Synchronization Problems!

Concurrency: Deadlock and Starvation. Chapter 6

Synchronization

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

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

OS Process Synchronization!

Transcription:

CSE 332: Locks and Deadlocks Richard Anderson, Steve Seitz Winter 2014 1

Recall Bank Account Problem class BankAccount { private int balance = 0; synchronized int getbalance() { return balance; } synchronized void setbalance(int x) { balance = x; } synchronized void withdraw(int amount) { int b = getbalance(); if(amount > b) throw setbalance(b amount); } // deposit would also use synchronized } Call to setbalance in withdraw - tries to lock this 2

Re-Entrant Lock A re-entrant lock (a.k.a. recursive lock) - If a thread holds a lock, subsequent attempts to acquire the same lock in the same thread won t block - withdraw can acquire the lock and setbalance can also acquire it - implemented by maintaining a count of how many times each lock is acquired in each thread, and decrementing the count on each release. Java synchronize locks are re-entrant 3

Locking Guidelines Correctness Consistency: make it well-defined Granularity: coarse to fine Critical Sections: make them small, atomic Leverage libraries 4

Consistent Locking Clear mapping of locks to resources - followed by all methods - clearly documented - same lock can guard multiple resources - what s a resource? Conceptual: - object - field 5 - data structure (e.g., linked list, hash table)

Lock Granularity Coarse grained: fewer locks, more objects per lock - e.g., one lock for entire data structure (e.g., linked list) - advantage: - disadvantage: Fine grained: more locks, fewer objects per lock - e.g., one lock for each item in the linked list 6

Lock Granularity Example: hashtable with separate chaining - coarse grained: one lock for whole table - fine grained: one lock for each bucket Which supports more concurrency for insert and lookup? Which makes implementing resize easier? Suppose hashtable maintains a numelements field. Which locking approach is better? 7

Critical Sections Critical sections: - how much code executes while you hold the lock? - want critical sections to be short - make them atomic : think about smallest sequence of operations that have to occur at once (without data races, interleavings) 8

Critical Sections Suppose we want to change a value in a hash table - assume one lock for the entire table - computing the new value takes a long time ( expensive ) synchronized(lock) { v1 = table.lookup(k); v2 = expensive(v1); table.remove(k); table.insert(k,v2); } 9

Critical Sections Suppose we want to change a value in the hash table - assume one lock for the entire table - computing the new value takes a long time ( expensive ) - will this work? synchronized(lock) { v1 = table.lookup(k); } v2 = expensive(v1); synchronized(lock) { table.remove(k); table.insert(k,v2); } 10

Critical Sections Suppose we want to change a value in the hash table - assume one lock for the entire table - computing the new value takes a long time ( expensive ) - convoluted fix: done = false; while(!done) { synchronized(lock) { v1 = table.lookup(k); } v2 = expensive(v1); synchronized(lock) { if(table.lookup(k)==v1) { done = true; // I can exit the loop! table.remove(k); table.insert(k,v2); }}} 11

Leverage Libraries Use built-in libraries whenever possible In real life, it is unusual to have to write your own data structure from scratch Implementations provided in standard libraries Point of CSE332 is to understand the key trade-offs, abstractions, and analysis of such implementations Especially true for concurrent data structures Very difficult to provide fine-grained synchronization without race conditions Standard thread-safe libraries like ConcurrentHashMap written by world experts 12

Another Bank Operation Consider transferring money: class BankAccount { synchronized void withdraw(int amt) { } synchronized void deposit(int amt) { } synchronized void transferto(int amt, BankAccount a) { this.withdraw(amt); a.deposit(amt); } } What can go wrong? 13

Deadlock x and y are two different accounts Time acquire lock for x withdraw from x block on lock for y acquire lock for y withdraw from y block on lock for x Thread 1: x.transferto(1,y) Thread 2: y.transferto(1,x) 14

Dining Philosopher s Problem 5 Philosopher s eating rice around a table one chopstick to the left and right of each first grab the one on your left, then on your right 15

Deadlock = Cycles Multiple threads depending on each other in a cycle T1 T2 T3 T2 has lock that T1 needs T3 has lock that T2 needs T1 has lock that T3 needs Solution? 16

How to Fix Deadlock? In Banking example class BankAccount { synchronized void withdraw(int amt) { } synchronized void deposit(int amt) { } synchronized void transferto(int amt, BankAccount a) { this.withdraw(amt); a.deposit(amt); } } 17

How to Fix Deadlock? Separate withdraw from deposit class BankAccount { synchronized void withdraw(int amt) { } synchronized void deposit(int amt) { } synchronized void transferto(int amt, BankAccount a) { this.withdraw(amt); a.deposit(amt); } } Problems? 18

Possible Solutions 1. transferto not synchronized exposes intermediate state after withdraw before deposit may be okay here, but exposes wrong total amount in bank 2. Coarsen lock granularity: one lock for each pair of accounts allowing transfers between them works, but sacrifices concurrent deposits/withdrawals 3. Give every bank-account a unique ID and always acquire locks in the same ID order Entire program should obey this order to avoid cycles 19

Ordering Accounts Transfer from bank account 5 to account 9 A5 A9 1. lock A5 2. lock A9 3. withdraw from A5 4. deposit to A9 20

Ordering Accounts Transfer from bank account 5 to account 9 Transfer from bank account 9 to account 5 A5 A9 A5 A9 1. lock A5 2. lock A9 3. withdraw from A5 4. deposit to A9 1. lock 2. lock 3. withdraw from 4. deposit to 21

Ordering Accounts Transfer from bank account 5 to account 9 Transfer from bank account 9 to account 5 A5 A9 A5 A9 1. lock A5 2. lock A9 3. withdraw from A5 4. deposit to A9 1. lock 2. lock 3. withdraw from 4. deposit to No interleavings will produce deadlock! T1 cannot block on A9 until it has A5 T2 cannot acquire A9 until it has A5 22

Banking Without Deadlocks class BankAccount { private int acctnumber; // must be unique void transferto(int amt, BankAccount a) { if(this.acctnumber < a.acctnumber) synchronized(this) { synchronized(a) { this.withdraw(amt); a.deposit(amt); }} else synchronized(a) { synchronized(this) { this.withdraw(amt); a.deposit(amt); }} } } 23

Lock Ordering Useful in many situations e.g., when moving an item from work queue A to B, need to acquire locks in a particular order Doesn t always work not all objects can be naturally ordered Java StringBuffer append is subject to deadlocks thread 1: append string A onto string B thread 2: append string B onto string A 24

Locking a Hashtable Consider a hashtable with many simultaneous lookup operations rare insert operations What s the right locking strategy? 25

Read vs. Write Locks Recall race conditions two simultaneous write to same location one write, one simultaneous read But two simultaneous reads OK Synchronize is too strict blocks simultaneous reads 26

Readers/Writer Locks A new synchronization ADT: The readers/writer lock A lock s states fall into three categories: not held held for writing by one thread held for reading by one or more threads 0 writers 1 0 readers writers*readers==0 new: make a new lock, initially not held acquire_write: block if currently held for reading or held for writing, else make held for writing release_write: make not held acquire_read: block if currently held for writing, else make/keep held for reading and increment readers count release_read: decrement readers count, if 0, make not held 27

In Java Java s synchronized statement does not support readers/writer Instead, library java.util.concurrent.locks.reentrantreadwritelock Different interface: methods readlock and writelock return objects that themselves have lock and unlock methods 28

Concurrency Summary Parallelism is powerful, but introduces new concurrency issues: Data races Interleaving Deadlocks Requires synchronization Locks for mutual exclusion Guidelines for correct use help avoid common pitfalls 29