Agenda. Highlight issues with multi threaded programming Introduce thread synchronization primitives Introduce thread safe collections

Similar documents
Synchronization for Concurrent Tasks

Concurrency: a crash course

Synchronising Threads

Synchronization COMPSCI 386

Concurrency, Thread. Dongkun Shin, SKKU

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

Deadlock. Concurrency: Deadlock and Starvation. Reusable Resources

CPSC/ECE 3220 Fall 2017 Exam Give the definition (note: not the roles) for an operating system as stated in the textbook. (2 pts.

Atomicity CS 2110 Fall 2017

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

Synchronization SPL/2010 SPL/20 1

CHAPTER 6: PROCESS SYNCHRONIZATION

Midterm 1, CSE 451, Winter 2001 (Prof. Steve Gribble)

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

CS370 Operating Systems

Chapter 6: Process Synchronization

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

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

Understanding Hardware Transactional Memory

CSC501 Operating Systems Principles. Process Synchronization

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

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

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

Review: Easy Piece 1

Process Synchronization. studykorner.org

The University of Texas at Arlington

The University of Texas at Arlington

Concept of a process

CS533 Concepts of Operating Systems. Jonathan Walpole

IV. Process Synchronisation

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

CS 220: Introduction to Parallel Computing. Introduction to CUDA. Lecture 28

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

CMSC421: Principles of Operating Systems

COP 4225 Advanced Unix Programming. Synchronization. Chi Zhang

Synchronization Spinlocks - Semaphores

The Java Memory Model

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

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

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

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

Synchronization. CSE 2431: Introduction to Operating Systems Reading: Chapter 5, [OSC] (except Section 5.10)

Threading and Synchronization. Fahd Albinali

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

More Types of Synchronization 11/29/16

What is the Race Condition? And what is its solution? What is a critical section? And what is the critical section problem?

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

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

Week 3. Locks & Semaphores

Reintroduction to Concurrency

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

Lesson 6: Process Synchronization

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

Operating Systems. Thread Synchronization Primitives. Thomas Ropars.

Chapter 2 Processes and Threads

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

Process Synchronization

Process Synchronization

Chapter 6: Process Synchronization

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

Programming in Parallel COMP755

Introduction to Locks. Intrinsic Locks

Models of concurrency & synchronization algorithms

Process Synchronization Mechanisms

Dealing with Issues for Interprocess Communication

Synchronization Principles

Chapter 6 Concurrency: Deadlock and Starvation

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

RCU in the Linux Kernel: One Decade Later

Interprocess Communication By: Kaushik Vaghani

Threads. Threads The Thread Model (1) CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5

Systèmes d Exploitation Avancés

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2.


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

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Lecture. DM510 - Operating Systems, Weekly Notes, Week 11/12, 2018

Concurrency and Synchronisation

Concurrency and Synchronisation

POSIX Threads: a first step toward parallel programming. George Bosilca

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

CS 153 Design of Operating Systems Winter 2016

CSE 120 Principles of Operating Systems

Lecture 8: September 30

Process Synchronization

Concurrent & Distributed Systems Supervision Exercises

Global shared variables. Message passing paradigm. Communication Ports. Port characteristics. Sending a message 07/11/2018

CS5460: Operating Systems

Last Class: Synchronization

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

CSCE Introduction to Computer Systems Spring 2019

Operating Systems. Synchronization

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

Last Class: Deadlocks. Today

Dept. of CSE, York Univ. 1

CS370 Operating Systems

Subject: Operating System (BTCOC403) Class: S.Y.B.Tech. (Computer Engineering)

Lecture 10: Avoiding Locks

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

Transcription:

Thread Safety

Agenda Highlight issues with multi threaded programming Introduce thread synchronization primitives Introduce thread safe collections 2 2

Need for Synchronization Creating threads is easy When threads share data problems can occur Inconsistent reads State corruption Synchronization fixes these problems, but potentially creates a new problem Over synchronization reduces scalability Lots of techniques to implement synchronization Each have cost and benefit Developers role is to write an application that scales and is thread safe, by selecting the best synchronization technique 3 3

Simple Increment Two threads Sharing an instance of Counter. Both are calling Increment 1000 times Question What is the value of count after both threads have completed? public class Counter protected int count; public virtual void Increment() count++; public int Value get return count; 4 4

time Simple Increment, NOT Atomic Even a simple count++ is not an atomic operation. Multiple CPU instructions that could be interweaved. Consider the possible execution below of two threads (T0, T1) Assuming count=0 at the start At the end of execution i would be 1 and not the desired 2. If two threads don t attempt to increment count at the same time not a problem. Spotting these kind of errors is hard T0: MOV R0,count T0: ADD R0,1 T1: MOV R0,count T0: MOV count,r0 T1: ADD R0,1 T1: MOV count,r0 5 5

Interlocked Modern CPU s expose special instruction set to perform various operations atomically Cost more than non atomic variants. Access to these instructions via Interlocked class Interlocked.Increment Interlocked.Decrement Interlocked.Add Interlocked.Exchange, Interlocked.CompareAndExchange Useful for building Spin locks public class InterlockedCounter : Counter public override void Increment() // Atomic count++ Interlocked.Increment(ref count); 6 6

Multi step state transition What happens if Thread A is inside ReceivePayment Thread B is inside NetWorth Can Interlocked help? class SmallBusiness decimal Cash = 0; decimal Receivables = 1000; public void ReceivePayment(decimal amount) Cash += amount; Receivables -= amount; public decimal NetWorth get return Cash + Receivables; 7 7

Sequential access To fix the problem Sequentialise access to the object state How Each instance of a reference type has a Monitor CLR guarantees that only one thread can own the monitor If a thread can t acquire the monitor it enters a wait state When the monitor is available it is woken up and proceeds Critical areas of code can therefore be protected by using a monitor. 8 8

Monitor based solution Only one thread in any critical region at any point in time private object _lock = new object(); public void ReceivePayment(decimal amount) Monitor.Enter(_lock); Cash += amount; Receivables -= amount; Monitor.Exit(_lock); Could be an issue with exceptions public decimal NetWorth get Deals better with exceptions Monitor.Enter(_lock); try return Cash + Receivables; finally Monitor.Exit(_lock); 9 9

Lock keyword Enter, try, finally, Exit common pattern C# language offers lock keyword to assist Compiler emits try, finally logic Use of Monitor.Enter and lock can lead to deadlocks Prefer Montior.TryEnter which takes a timeout Avoid using lock(this) and lock(typeof(x)) Less control over objects use for synchronization. Prefer creation of object for sole purpose of synchronization public void ReceivePayment(decimal amount) lock (_lock) Cash += amount; Receivables -= amount; 10 10

High Read to Write Ratio Monitor provides mutual exclusion behaviour Excluding readers and writers Thread safety not an issue if all threads read. Better throughput may be achieved with a Synchronization primitive that ensures There can be Many Readers, Zero Writer Or One Writer, Zero Readers This is known as a ReaderWriterLock.NET 3.5 and above prefer ReaderWriterLockSlim Pre 3.5, ReaderWriterLock Not well implemented, can result in writer being denied access for long periods of time. Often used for caching, where most of the time is spent reading with occasional updates. 11 11

Reader Writer Lock public class SimpleCache private Dictionary<int, string> cache= new Dictionary<int, string>(); private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); public string Get(int key) _lock.enterreadlock(); try return cache[key]; finally _lock.exitreadlock(); public void Set(int key, string val) _lock.enterwritelock(); try cache.add(key,val) finally _lock.exitwritelock(); Many threads can can read from the cache When one thread has the write lock no other thread can obtain read or write lock. 12 12

Synchronization across app domains Managed synchronization primitives only allow synchronization inside a single app domain How to control access to a shared file? Requires Kernel based synchronization Kernel synchronization can be achieved via managed wrappers Mutex Semaphore AutoResetEvent ManualResetEvent These synchronization primitives are orders of magnitude more expensive than managed ones 13 13

Summary A variety of ways to perform synchronization, the skill is picking the correct one Concurrent collections make it simpler to write efficient thread safe code Only use kernel synchronization primitives when absolutely necessary Analyse code and imagine worse possible race conditions 14 14