chapter 6: process synchronization · 2011-11-02 · operating system concepts – 8th edition,...
TRANSCRIPT
Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition,
Chapter 6: Process Synchronization
(프로세스 동기화)
6.2 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Module 6: Synchronization(동기화)
Background(배경)
The Critical-Section Problem(임계구역문제)
Peterson’s Solution(피터슨 솔루션)
Synchronization Hardware(동기화 하드웨어)
Semaphores(세마포)
Classic Problems of Synchronization(고전적 동기화문제들)
Monitors(모니터)
Synchronization Examples (동기화 사례)
Atomic Transactions(원자적트랜잭션)
6.3 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Objectives
To introduce the critical-section problem, whose solutions can be used to
ensure the consistency of shared data(공유데이터의 일관성을 보장하기
위한 임계구역 문제 소개)
To present both software and hardware solutions of the critical-section
problem(임계구역문제의 소프트웨어 및 하드웨어 솔루션)
To introduce the concept of an atomic transaction and describe
mechanisms to ensure atomicity(원자적 트랜잭션의 개념을 소개하고
원자성을 보장하기 위한 매카니즘을 기술한다.)
6.4 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Background
Concurrent access to shared data may result in data inconsistency
(공유데이터의 동시접근은 데이터의 불일치를 초래 할 수 있다.)
Maintaining data consistency requires mechanisms to ensure the
orderly execution of cooperating processes
(데이터의 일관성을 유지하기 위해서는 프로세스들의 실행순서를
보증하는 메커니즘이 요구된다.)
Suppose that we wanted to provide a solution to the consumer-
producer problem that fills all the buffers. We can do so by having
an integer count that keeps track of the number of full buffers.
Initially, count is set to 0. It is incremented by the producer after it
produces a new buffer and is decremented by the consumer after
it consumes a buffer.
(모든 버퍼를 사용하는 소비자-생산자문제에서 count 변수를
이용하여 소비실행순서를 보증하였다.)
6.5 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Previous Producer-Consumer (3.4.1)
Bounded Shared Buffer
Producer process
item nextProduced;
while (true) {
/* Produce an item in nextProduced */
while ((((in + 1) % BUFFER_SIZE) == out)
; /* do nothing -- no free buffers */
buffer[in] = nextProduced;
in = (in + 1) % BUFFER SIZE;
}
Consumer process
item nextConsumed;
while (true) {
while (in == out) ; // do nothing -- nothing to consume
nextConsumed = buffer[out];
// remove an item from the buffer
out = (out + 1) % BUFFER SIZE;
/* consume the item in nextConsume */
}
At most BUFFER_SIZE-1 items in the buffer of BUFFER_SIZE
Shared Data #define BUFFER_SIZE 10 typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0; //used by producer int out = 0; //used by consumer
6.6 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Previous Producer-Consumer (3.4.1)
New Shared Buffer with counter
Producer process
while (true) {
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
Consumer process
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in nextConsumed
}
Allow full buffer, BUFFER_SIZE items in the buffer of BUFFER_SIZE
Modified Producer Consumer define BUFFER_SIZE 10 typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0; int out = 0; int counter = 0;|
6.7 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bounded Buffer
The statements
counter++;
counter--;
must be performed atomically
(원자적으로 연산되어야 한다.)
Atomic operation means an operation that completes in its entirety without
interruption
(원자연산은 외부의 인터럽트 없이 완전히 실행되는 연산이다.)
6.8 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Race Condition(경합상태)
경합 상태(race condition) :
두 개의 프로세스가 경쟁적으로 한 변수를 조작
(예) 공유 변수 count의 변경 명령이 동시에 수행될 경우 불일치 발생
생산자의 count ++
register1 = count;
register1 = register1 + 1;
count = register1;
소비자의 counter --
register2 = count;
register2 = register2 -1;
count = register2;
병행 실행(concurrent execution)
T0: 생산자 register1 := count {register1 = 5}
T1: 생산자 register1 : = register1 + 1 {register1 = 6}
T2: 소비자 register2 := count {register2 = 5}
T3: 소비자 register2 := register2 - 1 {register2 = 4}
T4: 생산자 count := register1 {counter = 6}
T5: 소비자 count := register2 {counter = 4}
한 process만 접근하게 해야 함
6.9 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
An Example
Withdraw money from a bank account(은행계좌 인출문제)
Suppose you and your girl(boy) friend share a bank account with a
balance of 1,000,000won
What happens if both go to separate ATM machines, and
simultaneously withdraw 100,000won from the account?
(은행의 100만원을 두 사람이 다른 ATM에서 인출을 동시에 시도한다)
int withdraw (account, amount)
{
balance = get_balance (account);
balance = balance - amount;
put_balance (account, balance);
return balance;
}
6.10 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
An Example (Cont’d)
Interleaved schedules
Represent the situation by creating a separate thread for each person to do
the withdrawals
The execution of the two threads can be interleaved, assuming preemptive
scheduling:
6.11 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Solution to Critical-Section Problem(임계구역문제)
임계 구역
프로세스가 공유자료를 변경하는 코드영역
상호 배타적(mutually exclusive)이어야 함
프로세스 구조
진입 구역(entry section) : 진입허가 요청(한 프로세스만 실행)
출구 구역(exit section)
잔류 구역(remainder section)
임계 구역 해결을 위한 3 요구 조건(requirements)
R1. 상호 배제(mutual exclusion): 한 프로세스만 임계 구역 진입
R2. 진행(progress): 자연스럽게 막힘이 없이 진행, 임계구역에 진입할 프로세스
선택이 영원히 지연되지 않음
R3. 한계 대기(bounded waiting): 한 프로세스가 임계구역 진입 요청 후 기다리는데
한계가 있음(no starvation)
기본 기계 명령어들(load, store, test)들은 원자적으로 실행됨(executed
atomically)을 가정
6.12 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Solution to Critical-Section Problem
General structure for a typical process Pi
do {
entry section
critical section
exit section
remainder section
} while (TRUE);
6.13 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Mechanisms for Critical Sections
Locks
Very primitive, minimal semantics, used to build others
Semaphores
Basic, easy to get the hang of, hard to program with
Monitors
High-level, requires language support, implicit operations
Easy to program with: Java ―synchronized‖
Messages
Simple model of communication and synchronization based on (atomic)
transfer of data across a channel
Direct application to distributed systems
6.14 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Locks
Very primitive, minimal semantics, used to build others
Software Solutions
Peterson’s Solution for two process
Bakery Algorithm for n processes
Hardware Solutions
Mutual Exclusion solution using TestAndSet
Mutual Exclusion Solution using Swap Instruction
Bounded Mutual Exclusion solution using TestAndSet
6.15 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Locks
A lock is an object (in memory) that provides the following two operations:
acquire(): wait until lock is free, then grab it (lock가 해제될 때까지 가다린후 해제되면 잡는다)
release(): unlock, and wake up any thread waiting in acquire() (해제, 대기중인 쓰레드를 활성화한다)
Using locks
Lock is initially free
Call acquire() before entering a critical section, and release() after leaving it
Between acquire() and release(), the thread holds the lock
acquire() does not return until the caller holds the lock
At most one thread can hold a lock at a time
Locks can spin (a spinlock) or block (a mutex)
A mutex is an object in a program that serves as a lock and used to negotiate mutual exclusion among threads.
6.16 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Using Locks
6.17 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Implementing Locks (Cont’d)
Problem
Implementation of locks has a critical section, too!
The acquire/release must be atomic
A recursion, huh?
Atomic operation
Executes as though it could not be interrupted
Code that executes ―all or nothing‖
Solutions
Software-only algorithms
Algorithm for two processes
Bakery algorithm for more than two processes
Hardware atomic instructions
Test-and-set, compare-and-swap, etc.
Disable/re-enable interrupts
To prevent context switches
6.18 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Initial Attempts to Solve Problem
Only 2 processes, P0 and P1
General structure of process Pi (other process Pj)
Processes may share some common variables to synchronize their actions
Entry section
Acquire a lock
Exit section
Release a lock
do { entry section critical section exit section remainder section } while (1);
6.19 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Peterson’s Solution(software)
2개 프로세스의 S/W 임계구역문제 해법
LOAD 와 STORE 명령은 원자적(atomic)
즉, 수행 도중 절대 인터럽트 되지 않음
2개 프로세스가 아래 2개 변수 공유:
int turn;
Boolean flag[2]
변수 turn 은 어느 임계 구역 진입 순번 표시
The flag 배열은 임계 구역 진입 준비됨 표시
flag[i] = true 는 process Pi 가 준비되었음!
6.20 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Algorithm for Process Pi in Peterson’s solution
The structure of process Pi
do {
flag[i] = TRUE;
turn = j; //trigger Pj
while (flag[j] && turn == j);
critical section
flag[i] = FALSE;
remainder section
} while (TRUE);
Pi enter CS only when frag[j]==false or turn==i 동시 시도시 frag[i]==frag[j]==true => turn값 배타적, 상대방 trigger
The structure of process Pj do {
flag[j] = TRUE;
turn = i; //trigger Pi
while (flag[i] && turn == i);
critical section
flag[j] = FALSE;
remainder section
} while (TRUE);
6.21 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bakery Algorithm
Critical section for n processes(n 개 프로세스에 대한 임계구역문제)
Before entering its critical section, process receives a number. Holder of
the smallest number enters the critical section
If processes Pi and Pj receive the same number, if i < j, then Pi is
served first; else Pj is served first
The numbering scheme always generates numbers in increasing order
of enumeration; i.e., 1,2,3,3,3,3,4,5...
최소번호 수령
작은 번호를 받은 프로세스가 먼저실행한다.
6.22 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bakery Algorithm
Notation < lexicographical order (ticket #, process id #)
(a,b) < (c,d) if a < c or if a = c and b < d
max (a0,…, an-1) is a number, k, such that k >= ai for i = 0, …, n – 1
Shared data
Data structures are initialized to false and 0 respectively
boolean choosing[process]; //우선순위 받는 기간의미 int priority[process]; // process : process id #
6.23 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bakery Algorithm
Shared Varialbes
boolean choosing[p]; //우선순위 받기 위한 대기 상태
int priority[p]; // p : process id
initially choosing[..]=false; prioty[..]=0;
do {
choosing[p] = true; //프로세스 p가 우선순위 받는 모드 진입
priority [p] = max(priority[0], priority[1], …, priority[n – 1])+1;
choosing[p] = false; // //프로세스 p가 우선순위 받는 모드 종료
for (j = 0; j < n; j++) {
while (choosing[j]) ; //우선순위 받는 중이면 대기
while ((priority[j] != 0) && ((priority[j],j)< (priority[p], p))) ;
//다른 프로세스가 우선하면 그 프로세스의 처리까지 대기
}
critical section
priority[p] = 0;
remainder section
} while (1);
6.24 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Synchronization Hardware
Many systems provide hardware (instruction) support for critical section code
Uniprocessors – could disable interrupts(입터럽트 무력화)
Currently running code would execute without preemption
Generally too inefficient on multiprocessor systems
Operating systems using this not broadly scalable
Modern machines provide special atomic hardware instructions
Atomic = non-interruptable
Either test memory word and set value
Or swap contents of two memory words
6.25 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Synchronization Hardware
General s/w solution to Critical-section Problem Using Locks
do {
acquire lock
critical section
release lock
remainder section
} while (TRUE);
6.26 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Mutual Exclusion solution using TestAndSet
Mutual Exclusion using TestAndSet (hardware) instruction
Shared boolean variable lock., initialized to false.
Process Pi for mutual exclusion using TestAndSet atomic instruction initially lock =false; // global variable
do {
while ( TestAndSet (&lock )) ;
// critical section
lock = FALSE;
// remainder section
} while (TRUE); //hardware, Atomic instruction
boolean TestAndSet (boolean *target
{
boolean rv = *target;
*target = TRUE;
return rv:
}
do { while ( TestAndSet (&lock )) ; // critical section lock = FALSE; // remainder section } while (TRUE);
6.27 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Mutual Exclusion Solution using Swap Instruction
Mutual Exclusion Solution using Swap
Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key
Process Pi for mutual exclusion using Swap atomic instruction: initially lock=false //shared
do {
key = TRUE; //local variable
while ( key == TRUE)
Swap (&lock, &key );
// critical section
lock = FALSE;
// remainder section
} while (TRUE); void Swap (boolean *a, boolean *b) //hardware {
boolean temp = *a; *a = *b; *b = temp:
}
do { key = TRUE; //local variable while ( key == TRUE) Swap (&lock, &key ); // critical section lock = FALSE; // remainder section } while (TRUE);
6.28 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bounded-waiting Mutual Exclusion with TestandSet()
(유한대기 상호배제 소루션)
do {
waiting[i] = TRUE; //
key = TRUE;
while (waiting[i] && key) //proceed when waiting[i]==false or key(lock)=false
key = TestAndSet(&lock);
waiting[i] = FALSE;
// critical section
j = (i + 1) % n;
while ((j != i) && !waiting[j]) // i다음의 대기중 인프로세스를 활성화한다. Bounded waiting 보장 j = (j + 1) % n;
if (j == i)
lock = FALSE; // lock= false로 하여 다른 프로세스에게 허용 else
waiting[j] = FALSE; // lock==true 인 상태에서 Pj에서 wile문장을 지나 critical section 진입하게 한다.
// remainder section
} while (TRUE);
6.29 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
세마포어(Semaphore concept)
Semaphore is
A kind of general synchronization tool
Aslo is able to be sued as a synchronization tool that does not require busy waiting
Semaphore(신호기) S :
원자적 함수 wait() 과 signal()로 접근되는 정수변수 S
originally called P() and V(), (P from Duch proberen, ―to test‖. V from verhogen, to increment‖)
wait (S) { //atomic operation S:semaphor variable
while (S <= 0) ; // S>0 때까지 대기
S--;
}
signal (S) { //atomic operation
S++;
}
6.30 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Usage of Semaphor
Two types of semaphore Counting semaphore –무제한 정수처리, N개의 자원관리 공유시
Binary semaphore – 정수 0,1 ,mutex locks
An example of Binary semaphore
Process p with mutual exclusion using semaphore mutex.
Semaphore mutex=1; // initialized to 1 Shared data
do {
wait (mutex); // 1->0 or 다른 프로세스가 1로 설정할 때까지 busy waiting
// Critical Section
signal (mutex); // 0->1
// remainder section
} while (TRUE);
An example of Counting semaphore N개의 공유자원을 이용하기 위한 상호배제
Semaphore res=N ; //공유자원 수 : N
do {
Wait(res) //res— 자원이용하기 전 N==0이면 모든 자원이 사용중
// Critical Section
Signal(res) //res++ 자원 이용 후
// remainder section
} while(TRUE);
6.31 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Semaphore Implementation with no Busy waiting
기본 개념
Wait연산의 대기를 무한반복 대신에 대기큐에서 수행되도록 하여
시스템의 효율을 증가시킨다.
Semaphore 구조
typedef struct {
int value; //
struct process *L; //pointer to next record in the list
} semaphore;
Two operations:
block – 프로세스를 대기 큐에 추가하고 일시 중지
suspends the process, place the process invoking the
operation on the appropriate waiting queue.
wakeup –대기중인 큐의 포세스 한 개를 분리하여 ready
큐에 삽입하여 실행을 재개한다.
resumes the execution of a blocked process, remove one
of processes in the waiting queue and place it in the ready
queue.
6.32 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Semaphore Implementation with no Busy waiting (Cont.)
Implementation of wait:
wait(semaphore *S) { S->value--; //-value의 value는 대기중인 process의 수이다. if (S->value < 0) {
add this process to S->list; //add itself onto waiting list
block(); //자신의 프로세스는 대기큐로 이동 / 실행중지
} // 0 : 다른 프로세스 실행 방지시키고 자신은 계속 실행
}
Implementation of signal:
signal(semaphore *S) { S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P); // OS scheduler 의 ready queue로 이동시킨다.
} // >=1 : 다른 프로세스 실행을 허용 }
6.33 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Deadlock and Starvation
Deadlock
two or more processes are waiting indefinitely for an event(signal()) that can be caused by only one of the waiting processes (둘 또는 그 이상의 프로세스들이 대기 중인 프로세스 중 하나가 발생시킬 이벤트를 무한정 기다리고 있는 상태)
예
Let S and Q be two semaphores initialized to 1 where two processes P1,P2 (프로세스 P1,P2가 3개의 세마포 S,M를 다음과 같이 사용하면 발생가능)
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. . . . signal (S); signal (S);
signal (Q); signal (Q);
Starvation
indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended. (P0,P1모두 세마포 대기큐에 추가된 상태면 영원히 재 실행이 불가하다.)
6.34 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
6.6 Classical Problems of Synchronization
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
Semaphore 변수 사용
6.35 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bounded Buffer Problem
Synchronization with critical problem
initially in=out=counter=0
35
6.36 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Bounded Buffer Problem (Cont’d)
Implementation with semaphores
36
6.37 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
C#
Implementation with semaphores using C# language
Mutex mutex = new Mutex()
Semaphore empty = new Semaphore(N,N):
Semaphore full =new Semaphore(0,N):
void Produceer {
while (true)
{
T t = Produce();
empty.WaitOne(); //empty—
mutex.WaitOne(); //mutex—
Append(t);
mutex.ReleaseMutex(); //mutex++
full.Release(); //full++
}
37
void Consume er {
while (true)
{ full.WaitOne(); //full— mutex.WaitOne(); //mutex— T t = Take(); mutex.ReleaseMutex(); //mutex++
empty.Release(); //empty-- Consume(t);
}
6.38 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
using System.Text; using System.Threading; abstract class ProCon<T> { public ProCon(int maxBufferSize) { this.maxBufferSize = maxBufferSize; mutex = new Mutex(); full = new Semaphore(0, maxBufferSize); empty = new Semaphore(maxBufferSize, maxBufferSize);
} public void Producer(){ … } public void Consumer(){ … } abstract public T Take(); abstract public void Append(T t); abstract public T Produce(); abstract public void Consume(T t); } class MyProCon : ProCon<string> { protected List<string> list; public MyProCon(int maxSize) : base(maxSize) { list = new List<string>(maxSize); } override public T Take() {…} override public void Append(T t) {…} override public T Produce() {…} override public void Consume(T t) {…} }
class Program { public static void Main(string[] args) { MyProCon m = new MyProCon(4); Thread pro = new Thread(m.Producer); pro.Start(); // Thread pro2 = new Thread(m.Producer); //pro2.Start(); Thread con = new Thread(m.Consumer); con.Start(); Thread.Sleep(10000); //10초 정지 pro.Suspend(); con.Suspend(); //pro.Join(); //con.Join(); } }
Semaphore 와 mutex를 이용한 생산자-소비자문제(C#)
6.39 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
abstract class ProCon<T>
{
protected readonly int maxBufferSize;
protected Mutex mutex;
protected Semaphore full;
protected Semaphore empty;
public ProCon(int maxBufferSize)
{
this.maxBufferSize = maxBufferSize;
mutex = new Mutex();
full = new Semaphore(0, maxBufferSize);
empty = new Semaphore(maxBufferSize, maxBufferSize);
}
public void Producer()
{
while (true) {
T t = Produce();
empty.WaitOne(); //empty--
mutex.WaitOne(); //mutex--
Append(t);
mutex.ReleaseMutex(); //mutex++
full.Release(); //full++
}
}
public void Consumer()
{
while (true) {
full.WaitOne(); //full--
mutex.WaitOne(); //mutex--
T t = Take();
mutex.ReleaseMutex(); //mutex++
empty.Release(); //empty++
Consume(t);
}
}
//codes of critical section
abstract public T Take();
abstract public void Append(T t);
//non critical section
abstract public T Produce();
abstract public void Consume(T t);
}
class MyProCon : ProCon<string>
{
protected List<string> list;
public MyProCon(int maxSize) : base(maxSize)
{
list = new List<string>(maxSize);
}
//데이터 추가(저장) //critical codes
override public void Append(string t)
{
list.Add(t);
string s = "";
foreach (string a in list) s += a + " ";
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "\tadd : " + list.Count + "\t:" + s);
//Thread.Sleep(1000);
}
//데이터 소비 //critical codes :
override public string Take()
{
string t = list[0];
list.RemoveAt(0);
string s="";
foreach (string a in list) s += a + " ";
Console.WriteLine(Thread.CurrentThread.ManagedThreadId+"\tTake: " + list.Count + "\t:" +s);
Thread.Sleep(2000);
return t;
}
//데이터 생성
override public string Produce()
{
Random r = new Random();
int i = r.Next(10);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "\tPro: " +i);
return i.ToString();
}
//데이터 처리
override public void Consume(string t)
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "\tCon: " + t);
}
}
6.40 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
void Main() { MyProCon m = new MyProCon(4); Thread pro = new Thread(m.Producer); Thread con = new Thread(m.Consumer); pro.Start(); con.Start(); Thread.Sleep(10000); //10초 정지 pro.Suspend(); con.Suspend(); }
Producer
while (true) {
1 T t = Produce();
2 empty.WaitOne(); //empty--
3 mutex.WaitOne(); //mutex--
4 Append(t);
5 mutex.ReleaseMutex(); //mutex++
6 full.Release(); //full++
}
Consumer
while (true) {
1 full.WaitOne(); //full—
2 mutex.WaitOne(); //mutex—
3 T t = Take();
4 mutex.ReleaseMutex(); //mutex++
5 empty.Release(); //empty++
6 Consume(t);
}
3 1 Pro: 4 3 4 add : 1 :4 3 1 Pro: 4 4 3 Take: 0 : 3 4 add : 1 :4 3 1 Pro: 2 3 4 add : 2 :4 2 3 1 Pro: 2 3 4 add : 3 :4 2 2 3 Pro: 2 3 add : 4 :4 2 2 2 3 Pro: 2 4 Con: 4 4 Take: 3 :2 2 2 4 Con: 4 3 add : 4 :2 2 2 2 4 Take: 3 :2 2 2 3 Pro: 1 4 Con: 2 3 add : 4 :2 2 2 1 4 Take: 3 :2 2 1 3 Pro: 9 4 Con: 2 3 add : 4 :2 2 1 9 3 Pro: 8 4 Take: 3 :2 1 9 4 Con: 2
실행 결과 분석
6.41 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Readers-Writers Problem
복수의 reader 및 writer 프로세스들이 데이터집합을 공유하는
문제
Readers
읽기전용, 복수의 프로세스 읽기가능, 수정 불가능
Writers
읽고 쓰기 가능, writer 프로세스들끼리 배타적공유
6.42 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Readers-Writers Problem (Cont.)
Shared Data, initially
Semaphore mutex =1
//readcount 갱신시 상호배제용
Semaphore wrt = 1
//writer 상호배제
Integer readcount =0
// reading process
The structure of a writer process do {
wait (wrt) ;
//writing is performed
//wrt=0
signal (wrt) ; //wrt=1
} while (TRUE);
The structure of a reader process
do {
wait (mutex) ; //mutex=0
readcount ++ ;
if (readcount == 1)
wait (wrt); // 첫 번째 reading 시부터 읽는 동안 write 금지
signal (mutex)
// reading is performed , //복수프로세스가 동시 읽기 가능
wait (mutex) ;
readcount - - ;
if (readcount == 0)
signal (wrt) ; //모두(process) 읽으면 쓰기 허용
signal (mutex) ; //mutex=1 } while (TRUE);
6.43 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Dining-Philosophers Problem
Dining philosopher problem
Dijkstra, 1965
Life of a philosopher: Repeat
forever
Thinking
Getting hungry
Getting two chopsticks
Eating
The structure of Philosopher i:
Shared Data Semaphor chopstick [5] initialized to 1
philosohphor pi do {
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
} while (TRUE);
6.44 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Problems with Semaphores
Correct use of semaphore operations:
signal (mutex) …. wait (mutex)
wait (mutex) … wait (mutex)
Omitting of wait (mutex) or signal (mutex) (or both)
6.45 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Monitors concept
프로세스에서 세마포 변수를 잘못 사용하면 다양한 문제가 발생된다. 이런
문제를 해결하기 위하여 세마포변수 및 프로시듀어를 구조체(struct)안에
정의하고 추상화하고 프로그래머는 이 프로시듀어를 사용하여
세마포변수를 제어하므로서 프로그램머의 오류를 줄일 수 있다.
Signal(mutex)
//critical section
wait(mutex)
상호배제위반, 여러 프로세스가 동시실행, ..
Wait(mutex)
//critical section
wait(mutex)
교착상태
6.46 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Monitors
Monitor는 멤버를 을 캡슐화는 software module이다.
소프트웨어 모듈(구조체,클래스)이다.
공유데이터구조들과 공유데이터구조에서 실행되는 프로시주어들을 캡슐화한다.
이들 프로시쥬어를 호출하는 동시실행주인 프로세스간의 동기화
한번에 하나의 프로세스만인 활성화된다.
추상화된 데이터타입의 안전한 공유
Monitor syntax(struct)
monitor monitor-name
{
shared variable declarations
procedure P1 (…) { …. }
…
procedure Pn (…) {……}
Initialization code ( ….) { … }
…
}
}
6.47 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Monitors
Condition variable(개체)
모니터의 멤버 개체(일종의 struct)
condition x, y;
프로세스들이 모니터내에서 대기할 수 있는 수단
condition 개체의 멤버 operations wait and signal
x.wait();
프로세스가 호출, suspended 상태 진입
x.signal();
one suspended process를 재개시킨다.
만일 suspended 프로세스가 없으로 무시된다.
6.48 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Schematic view of a Monitor
waiting queue of processes trying to enter the monitor
at most one process in monitor at a time
6.49 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Monitor with Condition Variables
6.50 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Solution to Dining Philosophers
좌우의 이웃 철학자가 젓가락을 얻을 수 있을 때만 잡도록 강제한다.
양쪽의 철학자가 식사를 하지 않을 때만 식사한다.
전체 구조 monitor DP { pick(); putdown(); ……….. }
while(1) {
for all i in process Pi { think();
DP.pickup (i); eat(); DP.putdown (i); } }
6.51 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Monitor Solution to Dining Philosophers monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5]; void pickup (int i) { //
state[i] = HUNGRY; //상태를 hungry로
test(i); //죄우상태 점검에 따라서 식사모드 설정
if (state[i] != EATING) self [i].wait(); // 식사모드로 못 들어 갔으면 대기상태로
}
void putdown (int i) {
state[i] = THINKING; //사색모드로
// test left and right neighbors
test((i + 4) % 5); //우를 점검하여 식사 대기 중 이었으면 활성화 test((i + 1) % 5); //좌를 점검하여 식사 대기 중 이었으면 활성화
} void test (int i) {
if ( (state[(i + 4) % 5] != EATING) &&
(state[i] == HUNGRY) &&
(state[(i + 1) % 5] != EATING) ) //좌우 철학자가 식사중이 아니고 내가 { //배고프면
state[i] = EATING ; //내 상태를 식사모드로 설정
self[i].signal () ; // 대기 중 이었으면 자신을 활성화
}
}
void initialization code() { //모든 프로세스의 상태를 생각모드로
for (int i = 0; i < 5; i++)
state[i] = THINKING;
}
}
6.52 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
An example of a Monitor to Allocate Single Resource
하나의 자원을 할당해주는 모니터
monitor ResourceAllocator
{
boolean busy;
condition x;
void acquire(int time) {
if (busy)
x.wait(time); //time과 함께 저장 큐에
busy = TRUE;
}
void release() {
busy = FALSE;
x.signal();
}
initialization code() {
busy = FALSE;
}
}
프로세스에서 자원접근하는 방법 R.acquire(t) 자원접근 R.release() t: 자원접근요청 시간
6.53 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Synchronization Examples
Solaris
Windows XP
Linux
Pthreads
6.54 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Solaris Synchronization
Implements a variety of locks to support multitasking,
multithreading (including real-time threads), and
multiprocessing
Uses adaptive mutexes for efficiency when protecting
data from short code segments
Uses condition variables and readers-writers locks when
longer sections of code need access to data
Uses turnstiles to order the list of threads waiting to
acquire either an adaptive mutex or reader-writer lock
6.55 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Windows XP Synchronization
Uses interrupt masks to protect access to global resources on uniprocessor
systems
Uses spinlocks on multiprocessor systems
Also provides dispatcher objects which may act as either mutexes and
semaphores
Dispatcher objects may also provide events
An event acts much like a condition variable
6.56 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Linux Synchronization
Linux:
Prior to kernel Version 2.6, disables interrupts to implement short critical
sections
Version 2.6 and later, fully preemptive
Linux provides:
semaphores
spin locks
6.57 / 57 Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition
Pthreads Synchronization
Pthreads API is OS-independent
It provides:
mutex locks
condition variables
Non-portable extensions include:
read-write locks
spin locks
Hanbat National Univ. Computer Eng. Dept. Y.J.Kim © 2010 Operating System Concepts – 8th Edition,
End of Chapter 6