인천대학교 컴퓨터공학과 성미영 7.43 운영체제 Java Synchronization Synchronized, wait(), notify() statements Multiple Notifications Block Synchronization Java Semaphores.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Ch 7 B.
Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Chapter 6, Process Synchronization, Overheads, Part 2 1.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
02/05/2008CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying an earlier.
Silberschatz, Galvin, and Gagne  Applied Operating System Concepts Module 5: Threads Benefits User and Kernel Threads Multithreading Models Solaris.
1 Chapter 5 Threads 2 Contents  Overview  Benefits  User and Kernel Threads  Multithreading Models  Solaris 2 Threads  Java Threads.
Operating Systems CMPSC 473 Mutual Exclusion Lecture 13: October 12, 2010 Instructor: Bhuvan Urgaonkar.
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.
Synchronization Principles Gordon College Stephen Brinton.
Chapter 6: Process Synchronization Joe McCarthy CSS 430: Operating Systems - Process Synchronization1.
02/05/2007CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook.
Chapter 6: Process Synchronization. Outline Background Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems.
Silberschatz, Galvin and Gagne ©2007 Operating System Concepts with Java – 7 th Edition, Nov 15, 2006 Process Synchronization (Or The “Joys” of Concurrent.
02/02/2004CSCI 315 Operating Systems Design1 Java Threads Notice: The slides for this lecture have been largely based on those accompanying the textbook.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
02/14/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Adopted from and based on Textbook: Operating System Concepts – 8th Edition, by Silberschatz, Galvin and Gagne Updated and Modified by Dr. Abdullah Basuhail,
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
Operating Systems CSE 411 CPU Management Oct Lecture 13 Instructor: Bhuvan Urgaonkar.
Chapter 6, Process Synchronization, Overheads, Part 2 1.
Monitor  Giving credit where it is due:  The lecture notes are borrowed from Dr. I-Ling Yen at University of Texas at Dallas  I have modified them and.
7a.1 Silberschatz, Galvin and Gagne ©2003 Operating System Concepts with Java Module 7a: Classic Synchronization Background The Critical-Section Problem.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 6: Process Synchronization.
Internet Software Development More stuff on Threads Paul Krause.
Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly execution.
1 Java Threads and Synchronization Review Modified from slides taken from
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
6.3 Peterson’s Solution The two processes share two variables: Int turn; Boolean flag[2] The variable turn indicates whose turn it is to enter the critical.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization.
Silberschatz, Galvin, and Gagne  Applied Operating System Concepts Module 7: Process Synchronization Background The Critical-Section Problem.
Chap 6 Synchronization. Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms.
1 Chapter 7: Process Synchronization 2 Contents Background The Critical-Section Problem Synchronization Hardware Semaphores Classical Problems of Synchronization.
Chapter 6: Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Synchronization Background The Critical-Section.
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.
Advanced Concurrency Topics Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 CSC 539: Operating Systems Structure and Design Spring 2006 Process synchronization  critical section problem  synchronization hardware  semaphores.
1 Interprocess Communication (IPC) - Outline Problem: Race condition Solution: Mutual exclusion –Disabling interrupts; –Lock variables; –Strict alternation.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Chapter 6: Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware.
7.1 Process Synchronization Background The Critical-Section Problem Synchronization Hardware Semaphores Classical Problems of Synchronization Monitors.
인천대학교 컴퓨터공학과 성미영 운영체제 Java Synchronization ~ Synchronized, wait(), notify() statements Multiple Notifications Block Synchronization Java Semaphores.
Java Producer-Consumer Monitor From: Concurrent Programming: The Java Programming Language By Steven J. Hartley Oxford University Press, 1998.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization Codes.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
Chapter 6 Synchronization Dr. Yingwu Zhu. The Problem with Concurrent Execution Concurrent processes (& threads) often access shared data and resources.
6.1 Silberschatz, Galvin and Gagne ©2005 Operating System Principles 6.5 Semaphore Less complicated than the hardware-based solutions Semaphore S – integer.
Deadlock and Starvation
Threads Chate Patanothai.
Lecture 9: Process Synchronization
Lecture 9: Process Synchronization
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Semaphore Originally called P() and V() wait (S) { while S <= 0
Process Synchronization
Background Concurrent access to shared data can lead to inconsistencies Maintaining data consistency among cooperating processes is critical What is wrong.
Chapter 7: Synchronization Examples
Monitor Giving credit where it is due:
Chapter 6: Synchronization Tools
Presentation transcript:

인천대학교 컴퓨터공학과 성미영 7.43 운영체제 Java Synchronization Synchronized, wait(), notify() statements Multiple Notifications Block Synchronization Java Semaphores Java Monitors

인천대학교 컴퓨터공학과 성미영 7.44 운영체제 Java Synchronization Thread safe: 여러 thread 에 의해 동시에 접근되어도 데이터의 일관성 (data consistency) 을 보장할 수 있을 때 Synchronized Statement »Every object has a lock associated with it. »Calling a synchronized method requires “owning” the lock. »If a calling thread does not own the lock (another thread already owns it), the calling thread is placed in the wait set for the object’s lock. »The lock is released when a thread exits the synchronized method.

인천대학교 컴퓨터공학과 성미영 7.45 운영체제 Java Synchronization Entry Set

인천대학교 컴퓨터공학과 성미영 7.46 운영체제 Java Synchronization : 코딩할 것 »deadlock 가능 ( 어떻게 ? 왜 ?  교재 p235~p237) Synchronized enter() Method public synchronized void enter(Object item) { while (count == BUFFER_SIZE) Thread.yield(); ++count; buffer[in] = item; in = (in + 1) % BUFFER_SIZE; } Synchronized remove() Method public synchronized Object remove() { Object item; while (count == 0) Thread.yield(); --count; item = buffer[out]; out = (out + 1) % BUFFER_SIZE; return item; }

인천대학교 컴퓨터공학과 성미영 7.47 운영체제 Java Synchronization Entry and Waits Set

인천대학교 컴퓨터공학과 성미영 7.48 운영체제 Java Synchronization The wait() Method When a thread calls wait(), the following occurs: - the thread releases the object lock. - thread state is set to blocked. - thread is placed in the wait set. Notify Method When a thread calls notify(), the following occurs: - selects an arbitrary thread T from the wait set. - moves T to the entry set. - sets T to Runnable. T can now compete for the object’s lock again.

인천대학교 컴퓨터공학과 성미영 7.49 운영체제 Java Synchronization enter() with wait/notify Methods public synchronized void enter(Object item) { while (count == BUFFER_SIZE) try { wait(); } catch (InterruptedException e) { } } ++count; buffer[in] = item; in = (in + 1) % BUFFER_SIZE; notify(); } remove() with wait/notify Methods public synchronized Object remove() { Object item; while (count == 0) try { wait(); } catch (InterruptedException e) { } --count; item = buffer[out]; out = (out + 1) % BUFFER_SIZE; notify(); return item; }

인천대학교 컴퓨터공학과 성미영 7.50 운영체제 Java Synchronization Bounded Buffer 완전한 해법 public class BoundedBufferServer { public static void main(String args[]) { BoundedBuffer server = new BoundedBuffer(); // now create the producer and consumer threads Producer producerThread = new Producer(server); Consumer consumerThread = new Consumer(server); producerThread.start(); consumerThread.start(); }

인천대학교 컴퓨터공학과 성미영 7.51 운영체제 Java Synchronization import java.util.*; public class Producer extends Thread { public Producer(BoundedBuffer b) { buffer = b; } public void run() { Date message; while (true) { BoundedBuffer.napping(); // produce an item & enter it into the buffer message = new Date(); System.out.println("Producer produced " + message); buffer.enter(message); } private BoundedBuffer buffer; } import java.util.*; public class Consumer extends Thread { public Consumer(BoundedBuffer b) { buffer = b; } public void run() { Date message; while (true) { BoundedBuffer.napping(); // consume an item from the buffer System.out.println("Consumer wants to consume."); message = (Date)buffer.remove(); } private BoundedBuffer buffer; }

인천대학교 컴퓨터공학과 성미영 7.52 운영체제 Java Synchronization public class BoundedBuffer { public BoundedBuffer() { // buffer is initially empty count = 0; in = 0; out = 0; buffer = new Object[BUFFER_SIZE]; } // producer and consumer will call this to nap public static void napping() { int sleepTime = (int) (NAP_TIME * Math.random() ); try { Thread.sleep(sleepTime*1000); } catch(InterruptedException e) { } } public synchronized void enter(Object item) {…}; public synchronized Object remove() {…}; public static final int NAP_TIME = 5; private static final int BUFFER_SIZE = 5; private int count; // number of items in the buffer private int in; // points to the next free position in the buffer private int out; // points to the next full position in the buffer private Object[] buffer; }

인천대학교 컴퓨터공학과 성미영 7.53 운영체제 Java Synchronization public synchronized void enter(Object item) { while (count == BUFFER_SIZE) { try { wait(); } catch (InterruptedException e) { } } // add an item to the buffer ++count; buffer[in] = item; in = (in + 1) % BUFFER_SIZE; if (count == BUFFER_SIZE) System.out.println("Producer Entered “ + item + " Buffer FULL"); else System.out.println("Producer Entered “ + item + " Buffer Size = " + count); notify(); } public synchronized Object remove() { Object item; while (count == 0) { try { wait(); } catch (InterruptedException e) { } } // remove an item from the buffer --count; item = buffer[out]; out = (out + 1) % BUFFER_SIZE; if (count == 0) System.out.println("Consumer Consumed " + item + " Buffer EMPTY"); else System.out.println("Consumer Consumed " + item + " Buffer Size = " + count); notify(); return item; }

인천대학교 컴퓨터공학과 성미영 7.54 운영체제 Java Synchronization Database class with Java Synchronization public class Database { public Database() { readerCount = 0; dbReading = false; dbWriting = false; } public synchronized int startRead() { /* see next slides */ } public synchronized int endRead() { /* see next slides */ } public synchronized void startWrite() { /* see next slides */ } public synchronized void endWrite() { /* see next slides */ } private int readerCount; private boolean dbReading; private boolean dbWriting; }

인천대학교 컴퓨터공학과 성미영 7.55 운영체제 Java Synchronization Reader Methods public synchronized int startRead() { while (dbWriting == true) { try { wait(); } catch (InterruptedException e) { } } ++readerCount; if (readerCount == 1) dbReading = true; return readerCount; } public synchronized int endRead() { --readerCount if (readerCount == 0) dbReading = false; notifyAll(); return readerCount; } Writer Method public synchronized void startWrite() { while (dbReading == true || dbWriting == true) try { wait(); } catch (InterruptedException e) { } dbWriting = true; } public synchronized void endWrite() { dbWriting = false; notifyAll(); }

인천대학교 컴퓨터공학과 성미영 7.56 운영체제 Java Synchronization public class Reader extends Thread { public Reader(int r, Database db) { readerNum = r; server = db; } public void run() { int c; while (true) { System.out.println("reader " + readerNum + " is sleeping."); Database.napping(); System.out.println("reader " + readerNum + " wants to read."); c = server.startRead(readerNum); // you have access to read from the database System.out.println("reader " + readerNum + " is reading. Count = " + c); Database.napping(); c = server.endRead(readerNum); System.out.println("reader " + readerNum + " is done reading. Count = " + c); } private Databaseserver; private int readerNum; }

인천대학교 컴퓨터공학과 성미영 7.57 운영체제 Java Synchronization public class Writer extends Thread { public Writer(int w, Database db) { writerNum = w; server = db; } public void run() { while (true) { System.out.println("writer " + writerNum + " is sleeping."); Database.napping(); System.out.println("writer " + writerNum + " wants to write."); server.startWrite(writerNum); // you have access to write to the database System.out.println("writer " + writerNum + " is writing."); Database.napping(); server.endWrite(writerNum); System.out.println("writer " + writerNum + " is done writing."); } private Database server; private int writerNum; }

인천대학교 컴퓨터공학과 성미영 7.58 운영체제 Java Synchronization public class ReaderWriterServer { public static void main(String args[]) { Database server = new Database(); Reader[] readerArray = new Reader[NUM_OF_READERS]; Writer[] writerArray = new Writer[NUM_OF_WRITERS]; for (int i = 0; i < NUM_OF_READERS; i++) { readerArray[i] = new Reader(i, server); readerArray[i].start(); } for (int i = 0; i < NUM_OF_WRITERS; i++) { writerArray[i] = new Writer(i, server); writerArray[i].start(); } private static final int NUM_OF_READERS = 3; private static final int NUM_OF_WRITERS = 2; }

인천대학교 컴퓨터공학과 성미영 7.59 운영체제 Multiple Notifications notify() selects an arbitrary thread from the wait set. *This may not be the thread that you want to be selected. Java does not allow you to specify the thread to be selected. notifyAll() removes ALL threads from the wait set and places them in the entry set. This allows the threads to decide among themselves who should proceed next. notifyAll() is a conservative strategy that works best when multiple threads may be in the wait set.

인천대학교 컴퓨터공학과 성미영 7.60 운영체제 DoWork() public class DoWork { // pnum is the number of the thread that wishes to do some work public synchronized void DoWork(int pnum) { while (turn != pnum) { try { wait(); } catch (InterruptedException e) {} } // do some work for awhile System.out.println("Worker " + pnum + " will do some work"); try { Thread.sleep( (int) (Math.random() * 3000) ); } catch (InterruptedException e) { } // ok, we're finished. Now indicate to the next waiting // thread that it is their turn to do some work. System.out.println("Worker " + pnum + " is done working"); if (turn < 5) ++turn; else turn = 1; // change this to notifyAll() to see it run correctly! notify(); } private int turn = 1; }

인천대학교 컴퓨터공학과 성미영 7.61 운영체제 DoWork() public class Worker extends Thread { public Worker(DoWork p, String n, int i) { pile = p; name = n; num = i; } public void run() { while (true) { Runner.slacking(); pile.DoWork(num); } private DoWork pile; private String name; private int num; } public class Runner { public static void slacking() { try { Thread.sleep( (int) (Math.random() * 3000) ); } catch (InterruptedException e) { } } public class TestIt { public static void main(String args[]) { DoWork pile = new DoWork(); Worker[] bees = new Worker[5]; for (int i = 1; i <= 5; i++) bees[i-1] = new Worker(pile, "Worker “ + (new Integer(i)).toString(), i); for (int i = 1; i <= 5; i++) bees[i-1].start(); }

인천대학교 컴퓨터공학과 성미영 7.62 운영체제 Block Synchronization Blocks of code – rather than entire methods – may be declared as synchronized. This yields a lock scope that is typically smaller than a synchronized method. synchronized block 안에서 wait() 와 notify() 사용 가능 Object mutexLock = new Object();... public void someMethod() { // non-critical section synchronized(mutexLock) { // critical section } // non-critical section }

인천대학교 컴퓨터공학과 성미영 7.63 운영체제 Java Semaphores Java does not provide a semaphore, but a basic semaphore can be constructed using Java synchronization mechanism. public class Semaphore { public Semaphore() { value = 0; } public Semaphore(int v) { value = v; } public synchronized void P() { while (value <= 0) { try { wait(); } catch (InterruptedException e) { } } value --; } public synchronized void V() { ++value; notify(); } private int value; }

인천대학교 컴퓨터공학과 성미영 7.64 운영체제 Java Semaphores Java 의 동기화 규칙 (synchronization rules) 1. 하나의 thread 는 어떤 객체의 lock 을 가진 상태에서 그 객체에 대한 다른 synchronized method ( 또는 block) 에 진입할 수 있다. 2. 하나의 thread 는 다른 객체에 대한 synchronized method 호출을 내포 (nest) 할 수 있다. 즉, 하나의 thread 는 동시에 여러 개의 다른 객체에 대한 lock 을 소유할 수 있다. 3.synchronized 로 선언되어 있지 않은 어떤 객체의 method 는 그 객체에 대하여 다른 synchronized method 가 실행 중일 지라도 lock 의 소유에 상관없이 그 객체에 대한 method 를 호출할 수 있다. 4. 만일 어떤 객체에 대한 wait set 가 비어있다면 notify() 나 notifyAll() 은 아무 영향을 주지 않는다. Java Monitor »Java synchronization 의 lock 은 모니터처럼 동작 » 모든 Java 객체는 연관된 monitor 를 가짐 »Java 는 이름 없는 하나의 조건변수 (a unnamed condition variable) 를 가지는 모니터 condition.wait : wait() condition.signal: notify(), notifyAll() notify(), notyfyAll() 로 깨어난 thread 는 스스로 조건이 맞는지 조사 »Java monitor 는 signal-and-continue 접근

인천대학교 컴퓨터공학과 성미영 7.65 운영체제 Solaris 2 에서의 동기화 (Synchronization in Solaris 2) 1. 적응성 (adaptive) mutexes : 짧은 임계구역에 i) multiprocessor system 에서 처음에는 표준 세마포어처럼 동작 (spinlock) 하다 사용하려는 데이터가 lock 되었을 때 ① lock 한 프로세스가 running thread 이면 그대로 spinlock 하다가 진행 ② lock 한 프로세스가 running thread 아니면 (spinlock 시간이 길어짐 ) sleeping thread 로 처리 : block 되어 sleep 했다가 wakeup 됨 ( 바쁜 대기 없는 세마포어 처럼 ) ii) uniprocessor system 에서 항상 sleeping thread 로 처리 » 다른 thread 가 lock test 하는 순간 이미 CPU 는 다른 thread 처리 중이므로 2. 조건 변수 (Condition variable) 와 세마포어 : 긴 임계구역에 »lock 되었으면 thread 는 wait and sleeps »lock 을 푸는 스레드가 signal 3. 판독자 - 기록자 잠금 (readers-writers locks) : 긴 임계구역에 » 대부분의 경우 read-only 인 data 보호 »semaphore 보다 유리 (multiple reads 가능하므로 ) 커널의 락킹 메커니즘은 사용자 수준 스레드도 그대로 사용 가능, 단 커널 락킹만 커널 우선순위 상속함 (kernel priority inheritance)

인천대학교 컴퓨터공학과 성미영 7.66 운영체제 Windows NT Synchronization Windows NT Provides: »mutex( 뮤텍스 ) 스레드가 공유 데이터 접근 위해 사용 »critical sections( 임계구역 ) 같은 프로세스의 스레드 사이의 동기화를 제공하는데 사용 »semaphores( 세마포어 ) »event objects( 사건 객체 ) 조건 변수와 유사한 동기화 객체 원하는 조건이 일어났을 때 하나의 대기 스레드에게 통보 (notify)

인천대학교 컴퓨터공학과 성미영 7.67 운영체제 수업 류시화 엮은 잠언시집 : 지금 알고 있는 걸 그때도 알았더라면 중에서 그때 예수께서 제자들을 산으로 데리고 올라가 곁에 둘러앉히시고 이렇게 가르치셨다. 마음이 가난한 사람은 행복하다. 하늘나라가 그들의 것이다. 온유한 사람은 행복하다. 슬퍼하는 사람은 행복하다. 자비를 베푸는 사람은 행복하다. 박해받는 사람은 행복하다. 고통받는 사람은 행복하다. 하늘나라에서의 보상이 크니 기뻐하고 즐거워하라. 그러자 시몬 베드로가 말했다. “ 그 말씀을 글로 적어 놓으리까 ?” 그리고 안드레아가 말했다. “ 그 말씀을 잘 새겨 둬야 할까요 ?” 그러자 야고보가 말했다. “ 그걸 갖고 우리끼리 시험을 쳐볼까요 ? 그러자 빌립보가 말했다. “ 우리가 그 뜻을 잘 모를 경우에는 어떻게 할까요 ?” 그리고 바돌로메가 말했다. “ 우리가 이 말씀을 다른 사람들에게 전해 줘야 할까요 ?” 그러자 요한이 말했다. “ 다른 제자들한테는 이런 걸 알려줄 필요가 있을까요 ?” 그러자 마태오가 말했다. “ 우리는 여기서 언제 떠날 건가요 ?” 그리고 유다가 말했다. “ 그 말씀이 실생활과는 어떤 관계가 있는 걸까요 ?” 그리고 그 자리에 참석했던 바리새인 하나는 예수에게 수업 계획서를 보여 줄 것을 요청하면서 그 가르침의 최종적인 목표가 무엇이냐고 물었다. 그러자 예수께서는 우셨다. 작자 미상 M. 스콧 펙 제공