Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Practice Session 7 Synchronization Liveness Deadlock Starvation Livelock Guarded Methods Model Thread Timing Busy Wait Sleep and Check Wait and Notify.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 6 Process Synchronization Bernard Chen Spring 2007.
Chapter 6: Process Synchronization
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
1 Concurrency: Mutual Exclusion and Synchronization Chapter 5.
1 Lecture 18 Further Threading Overview  Case Study: Cooperating Threads  Producer/ Consumer model threads  Waiting for Synchronized Data  Busy Waiting.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
Monitors Chapter 7. The semaphore is a low-level primitive because it is unstructured. If we were to build a large system using semaphores alone, the.
Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles, 6/E William Stallings Patricia Roy Manatee.
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.
© Andy Wellings, 2004 Roadmap  Introduction  Concurrent Programming  Communication and Synchronization  Completing the Java Model  Overview of the.
Chapter 6: Process Synchronization. Outline Background Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems.
Concurrency CS 510: Programming Languages David Walker.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
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.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
Concurrency - 1 Tasking Concurrent Programming Declaration, creation, activation, termination Synchronization and communication Time and delays conditional.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Internet Software Development More stuff on Threads Paul Krause.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Introduction to Concurrency.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
Internet Software Development Controlling Threads Paul J Krause.
Threading Eriq Muhammad Adams J
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
OPERATING SYSTEMS Frans Sanen.  Recap of threads in Java  Learn to think about synchronization problems in Java  Solve synchronization problems in.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Threading and Concurrency COM379T John Murray –
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
 2002 Prentice Hall, Inc. All rights reserved. Outline HoldIntegerUnsyn chronized.java Line 4 Lines 7-13 Lines // Fig. 15.6: HoldIntegerUnsynchronized.java.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
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.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Multithreading / Concurrency
Multi Threading.
Threads and Concurrency in Java: Part 2
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Synchronization Lecture 23 – Fall 2017.
Monitors Chapter 7.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Thread Synchronization
Race Conditions & Synchronization
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Monitors Chapter 7.
Concurrency: Mutual Exclusion and Process Synchronization
Monitors Chapter 7.
CSE 451: Operating Systems Autumn 2003 Lecture 7 Synchronization
Threads and Multithreading
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación y sincronización de Procesos

Comunication&Synchronization threads 2 Properties of Concurrent Processes Concurrent programs are governed by two key principles. The "safety" principle states "nothing bad can happen". The "liveness" principle states "eventually, something good happens".

Comunication&Synchronization threads 3 Safety Safety in general means that only one thread can access the data at a time, and ensures that the data remain in a consistent state during and after the operation. Safety is ensured by implementing * "mutual exclusion" and * "condition synchronization" when operating on shared data.

Comunication&Synchronization threads 4 "Mutual exclusion" means that that only one thread can access the data at a time, and ensures that the data remain in a consistent state during and after the operation. (atomic update). "Condition synchronization" means that operations may be delayed if shared resources are in the wrong state (e.g., read from empty buffer).

Comunication&Synchronization threads 5 Liveness Mutual exclusion solves many safety issues, but gives rise to other problems, in particular deadlock and starvation. The problem of deadlock arises when a thread holds a lock on one object and blocks attempting to gain a lock on another object, because the second object is already locked by a different thread, which is blocked by the lock the original thread currently holds.

Comunication&Synchronization threads 6 Both threads settle down to wait for the other to release the necessary lock, but neither thread will ever release their own lock because they are both blocked waiting for the other lock to be released first. Deadlock is one of the most common concurrent programming bugs.

Comunication&Synchronization threads 7 Starvation Starvation occurs when a thread cannot proceed because it cannot gain access to a resource it requires.

Comunication&Synchronization threads 8 Continuación Liveness is gradational. Programs can be ‘nearly’ dead or ‘not very’ live. Every time you use a synchronized method, you force sequential access to an object. If you have a lot of threads calling a lot of synchronized methods on the same object, your program will slow down a lot.

Comunication&Synchronization threads 9 Communication & Synchronization There are different Synchronization Techniques: * Procedure Oriented (Busy-Waiting, Semaphores, Monitors) * Message Oriented (Message Passing) * Operation Oriented (Remote Procedure Call)

Comunication&Synchronization threads 10 Synchronizing Threads In a general case, concurrent threads share data and analyze activities of other threads. In Object-Oriented programming, sharing data is equivalent to sharing an objec

Comunication&Synchronization threads 11 Example. public class Producer extends Thread { private IS storage_; public Producer(IS storage) { storage_ = storage; } public void run() { for (int i = 0; i < 10; i++) { storage_.put(i); System.out.println ("Producer put: " + i); } } } public class Consumer extends Thread { private IS storage_; public Consumer(IS storage) { storage_ = storage; } public void run() { int value; for (int i = 0; i < 10; i++) { value = storage_.get(); System.out.println ("Consumer got: " + value); } } }

Comunication&Synchronization threads 12 Cont. public class IS { private int value_; public void put(int value){value_ = value;} public int get(){return value_;} } The main program starting all the threads and creating a shared instance of IS might look as follows: IS storage = new IS(); Producer producer = new Producer(storage); Consumer consumer = new Consumer(storage); producer.start(); consumer.start();

Comunication&Synchronization threads 13 We might notice the following problems. One problem arises when the Producer is quicker than the Consumer and generates two numbers before the Consumer has a chance to consume the first one. Thus the Consumer would skip a number. Part of the output might look like this: Producer put: 0 Producer put: 1 Consumer got: 1 Another problem that might arise is when the Consumer is quicker than the Producer and consumes the same value twice. In this situation, the Consumer would print the same value twice and might produce output that looked like this: Producer put: 0 Consumer got: 0

Comunication&Synchronization threads 14 Race conditions. Problems like this one are called race conditions. They arise from multiple, asynchronously executing threads trying to access a single object at the same time and getting the wrong result.

Comunication&Synchronization threads 15 The activities of the Producer and Consumer must be synchronized in two ways: First Two threads must not simultaneously access the shared object. A Java thread canprevent such simultaneous access by locking an object. When an object is locked by one thread and another thread invokes a synchronized method on the same object, the second thread will block until the object is unlocked. Second Two threads must coordinate their Put/Get operations. For example, the Producer indicates that the value is ready, and the Consumer indicate that the value has been retrieved.

Comunication&Synchronization threads 16 Some methods to synchronization The Thread class provides a collection of methods - wait, notify, and notifyAll - to build such co-ordination mechanisms. The code segments within a program that access the same object from separate, concurrent threads are called critical sections. A critical section is a block or a method identified with the synchronized keyword. Java associates a lock with every object that has synchronized code.

Comunication&Synchronization threads 17 Note that the method declarations for both put and get contain the synchronized keyword. Hence, the system associates a unique lock with every instance of IntegerStorage (including the one shared by the Producer and the Consumer). public class IS { private int value_; public synchronized void put(intvalue){value_ = value;} public synchronized int get(){return value_;} }

Comunication&Synchronization threads 18 Now, we want the Consumer to wait until the Producer puts a value into the IS and the Producer must notify the Consumer when it happened. Similarly, the Producer must wait until the Consumer takes a value (and notifies the Producer) before replacing it with a new value.

Comunication&Synchronization threads 19 public class IntegerStorage { private int value_; private boolean available_ = false; public synchronized void put(int value){ while(available_) { try {wait();} // wait for Consumer to get value catch (InterruptedException exc) {exc.printStackTrace();} } value_ = value; available_ = true; // notify Consumer that value has been set notifyAll(); } public synchronized int get() { while(!available_){try {wait();} // wait for Producer to put value catch (InterruptedException exc) {exc.printStackTrace();} } available_ = false; // notify Producer that value has been retrieved notifyAll(); return value_; }

Comunication&Synchronization threads 20 Ejemplo: Hola Mundo Sincronizado class SyncTest extends Thread { String msg; public SyncTest(String s) { msg = s; start(); } public void run() { synchronized (SyncTest.class) { System.out.print("[" + msg); try { Thread.sleep(1000); } catch (InterruptedException e) {}; System.out.println("]"); } public static void main(String [] args) { new SyncTest("Hello"); new SyncTest("Synchronized"); new SyncTest("World"); } }

Comunication&Synchronization threads 21 ¿Qué aprendieron? Puntos importantes de la sesión