Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.

Slides:



Advertisements
Similar presentations
Operating Systems Part III: Process Management (Process Synchronization)
Advertisements

50.003: Elements of Software Construction Week 6 Thread Safety and Synchronization.
CS492B Analysis of Concurrent Programs Lock Basics Jaehyuk Huh Computer Science, KAIST.
Chapter 6: Process Synchronization
5.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 5: CPU Scheduling.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Threading Part 4 CS221 – 4/27/09. The Final Date: 5/7 Time: 6pm Duration: 1hr 50mins Location: EPS 103 Bring: 1 sheet of paper, filled both sides with.
Threading Part 3 CS221 – 4/24/09. Teacher Survey Fill out the survey in next week’s lab You will be asked to assess: – The Course – The Teacher – The.
Semaphores. Announcements No CS 415 Section this Friday Tom Roeder will hold office hours Homework 2 is due today.
5.6.2 Thread Synchronization with Semaphores Semaphores can be used to notify other threads that events have occurred –Producer-consumer relationship Producer.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 What is the “volatile” Keyword? You can skip locking (thread synchronization) in some cases by using the volatile variables. –No locking/unlocking =
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
A. Frank - P. Weisberg Operating Systems Introduction to Cooperating Processes.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Nachos Phase 1 Code -Hints and Comments
Threads some important concepts Simon Lynch
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
Optimistic Design 1. Guarded Methods Do something based on the fact that one or more objects have particular states  Make a set of purchases assuming.
COMP 111 Threads and concurrency Sept 28, Tufts University Computer Science2 Who is this guy? I am not Prof. Couch Obvious? Sam Guyer New assistant.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Concurrency in Java Brad Vander Zanden. Processes and Threads Process: A self-contained execution environment Thread: Exists within a process and shares.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Optimistic Design CDP 1. Guarded Methods Do something based on the fact that one or more objects have particular states Make a set of purchases assuming.
Implementing Lock. From the Previous Lecture  The “too much milk” example shows that writing concurrent programs directly with load and store instructions.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Loops Tonga Institute of Higher Education. Introduction Programs need to be able to execute tasks repeatedly. Use loops to repeat actions  For Loop 
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Implementing Mutual Exclusion Andy Wang Operating Systems COP 4610 / CGS 5765.
Lecture 5 Page 1 CS 111 Summer 2013 Bounded Buffers A higher level abstraction than shared domains or simple messages But not quite as high level as RPC.
Advanced Programming Concurrency and Threads Advanced Programming. All slides copyright: Chetan Arora.
Concurrency 2 CS 2110 – Spring 2016.
Multithreading / Concurrency
Background on the need for Synchronization
Atomic Operations in Hardware
Atomic Operations in Hardware
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Synchronization Lecture 23 – Fall 2017.
The C++ Memory model Implementing synchronization)
Module 7a: Classic Synchronization
Threads and Memory Models Hal Perkins Autumn 2009
Thread Synchronization
Coordination Lecture 5.
Java Concurrency 17-Jan-19.
Java Concurrency.
CS333 Intro to Operating Systems
Chapter 6: Synchronization Tools
Java Concurrency.
Threads and Multithreading
Java Concurrency 29-May-19.
CSE 332: Concurrency and Locks
some important concepts
Presentation transcript:

Threading Part 2 CS221 – 4/22/09

Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages for a period of time – If it takes too long the Main thread will interrupt it Uses: – Thread.start – Thread.sleep – Thread.join – Thread.isAlive – Thread.interrupt

Thread Communication Threads communicate through shared memory You can share across threads anything that you could share within a single thread: – Object instances – Fields and methods on objects – Etc Special communication actions can be accomplished via the Thread object – Join, sleep, interrupt, etc.

Thread Communication The good: – It is very efficient The bad: – Thread interference – Memory consistency problems

Thread Interference Interference occurs when two threads modify the same data at the same time If operations interleave, rather than completing atomically, you have a problem

Example

Increment can be decomposed into atomic operations: – Retrieve C – Increment C by 1 – Store the new value into C Decrement – Retrieve C – Decrement C by 1 – Store the new value into C

Example Imagine: – Thread 1 calls increment – Thread 2 calls decrement What will happen?

Example Hard to say actually! Here is one possibility: – Thread 1: Retrieve C – Thread 2: Retrieve C – Thread 1: Increment stored value (0->1) – Thread 2: Decrement stored value (0->-1) – Thread 1: Store value into C (C=1) – Thread 2: Store value into C (C=-1)

Example This interleaving of operations results in the value of Thread 1’s operations being overwritten Order of execution could be different every time: – Thread 1’s value is overwritten – Thread 2’s value is overwritten – No error

Example

Memory Consistency Errors Results when two threads have inconsistent views of the same data Can happen even if you solve the previous problem and ensure the writes are atomic – If Thread 1 modifies data and Thread 2 reads that data, it may not yet be committed to memory – Thread 2 may get the old value…

Example Counter is initialized: int counter = 0; First, Thread 1: Counter++; Next, Thread 2: System.out.println(counter); We know that (counter == 1) is true for Thread 1 We cannot guarantee that (counter == 1) is true for Thread 2

Scary! How do we solve these problems? Thread Synchronization! Some we already know: – Thread.start: Guarantees all actions performed by the originating thread are synchronized to the new thread. – Thread.join: When a join returns due to termination, all actions from that thread are synchronized to the originating thread.

Thread Synchronization Thread synchronization is - Coordinating simultaneous threads so that you: – Guarantee the correct runtime order of operations – Avoid race conditions which could result in thread interference or memory consistency problems

Thread Synchronization How do you do accomplish thread synchronization? Data integrity options: – Synchronized methods – Synchronized statements using locks – Atomic data access – Immutable objects Order of operations options: – Guarded blocks – Locks

Synchronized Methods It is impossible for two threads to interleave on a synchronized method – While Thread 1 is in the method, Thread 2 is blocked Guarantees memory consistency – When Thread 1 exits the method, Thread 2 is guaranteed to see the same data

Synchronized Methods If a method can be called by two threads… …Use synchronize keyword to ensure data integrity within that method public synchronized void decrement()

Example

Intrinsic Locks Every object is associated with an intrinsic lock In order for a thread to get exclusive access to an object, it must: – Acquire the lock before access – Release the lock when it is done When a thread acquires a lock, no other thread can acquire the same lock Synchronized methods do a lot behind the scenes: – Thread 1 acquires lock for the Counter object – Thread 1 calls increment method() – Thread 2 tries to acquire the lock – Thread 2 blocks – Thread 1 releases the lock – Thread 2 acquires lock for the Counter object – Thread 2 calls decrement() method

Synchronized Statements Blocking on an entire object can cause performance problems Synchronized statements give you more control over the acquisition and release of locks Much easier to make a mistake – be careful!

Example 1

Example 2

Atomic Data Access Atomic Action: An action that is indivisible and cannot be interrupted until it is complete. Is counter ++; atomic? How do you ensure an action is atomic?

Volatile Keyword The volatile keyword ensures that all access to a variable will be atomic private volatile int c = 0; Volatile keyword tells Java that this variable will be accessed by multiple threads

Volatile What it gives you: – Ensures memory consistency – Ensures atomic read operations on the variable – Ensures atomic write operations on the variable What it does not give you: – Read+Update+Write is still not atomic What does this mean?

Example

Volatile When should volatile be used? – You write a variable in one thread – You check it in another Typical scenario: – You have a boolean flag that two threads can access – Thread 1 sets the value to true – Thread 2 checks to see if the value is true before taking some action