7 장 프로세스 동기화 ii 2015-04-13. 7.5 동기화의 전통적 문제 1. 유한 버퍼...
TRANSCRIPT
7 장 프로세스 동기화 II
04/18/23
7.5 동기화의 전통적 문제1. 유한 버퍼 문제
전제조건 :
버퍼풀은 n 개로 구성되어 있으며 , 각각은 하나의 항목을 보관할 수 있다 .
Mutex 세마포어 버퍼풀에 접근하기 위한 상호배제 값은 1 로 초기화
Empty 와 full 세마포어 계속하여 버퍼가 empty 와 full 인지를 계산 세마포어 empty 는 값 n 으로 초기화 세마포어 full 은 값 0 으로 초기화
7.5 Classical Problem of Synchronization
do {
Produce an item in nextp
wait( empty ); // Notify getting resources to another processes wait( mutex ); // Get mutual exclusion about resource
add nextp to buffer // Produce full buffers for the consumer
signal( mutex ); // Release mutual exclusion signal( full ); // Notify releasing resources
} while (1)
생산자 프로세스의 구조
7.5 Classical Problem of Synchronization
do {
wait(full); // Notify getting resources to another processes wait(mutex); // Get mutual exclusion about resource
remove an item from buffer to nextc
Produce empty buffers for the producer signal(mutex); // Release mutual exclusion signal(empty); // Notify releasing resources
consume the item in nextc
} while(1)
소비자 프로세스 구조
7.5 Classical Problem of Synchronization
2. readers-writers 문제 (1) 데이터 객체 (file or record 등 ) 는 여러 개의 병행
프로세스에 의해서 공유된다 . 프로세스의 두가지 형태
Reader : 읽기만 하는 프로세스 Writer : 읽고 쓰는 프로세스 만약 writer 와 함께 다른 프로세스 (reader 혹은 writer) 가
동시에 공유 객체에 접근할 경우 Chaos
reader-writer problem 1st readers-writers 문제 Solution : writer 가 공유 객체에 대한 권한을 받은 경우가
아니면 reader 는 기다리지 않는다 . 2nd readers-writers 문제 Solution : writer 는 준비되면 최대한 빨리 실행한다 . Writer
가 기다리면 , 새로운 reader 는 허용되지 않는다 .
7.5 Classical Problem of Synchronization
2. readers-writers 문제 (2) 각 해결책은 starvation 을 야기시킬 수 있다 .
1st case - Writers’ starvation 2nd case - Readers’ starvation
해결책 첫번째 해결책에 starvation 이 없는 방법 제시
semaphore mutex, wrt;
int readcount;
mutex, wrt – 세마포어이며 값는 1 로 초기화readcount – 값은 0 으로 초기화 wrt semaphore : reader 와 writer 에게 공용 writer 프로세스는 상호배제 mutex semaphore : readcount 가 수정될 때 상호배제를 보증 readcount : 객체를 읽은 프로세스 수
7.5 Classical Problem of Synchronization
wait( wrt );
writing is performed
signal( wrt );
wait( mutex );readcount++;if (readcount == 1) wait( wrt );signal( mutex ); · · · ·
reading is performed · · · · wait( mutex );readcount--;if (readcount == 0) signal( wrt );signal( mutex );
writer 프로세스 구조
reader 프로세스 구조
7.5.3 철학자들의 만찬 문제 전통적인 동기화 문제
Allocate several resources among several processes in a deadlock and starvation-free manner
•5 명의 철학자는 단지 생각하고 먹기만 한다 .• 다섯개의 밥그릇과 젓가락이 있다 .•철학자는 한번에 하나의 젓가락을 집을 수 있다 .• 철학자는 동시에 두개의 젓가락을 모두 잡았을 때 식사를 할수 있고 , 식사중에는 젓가락을 놓지 않는다 .
7.5 The Dining-Philosophers Problem
해결책 1 각 젓가락의 세마포어 값을 1 로 초기화 젓가락 잡기 - a wait operation on that semaphore 젓가락 놓기 - a signal operation on the appropriate semaph
ores
이웃하는 두사람이 동시에 식사하지 않는다고 보장한다 . 그러나 이 해결책은 교착상태를 발생시킬 가능성이 있다 .
All philosophers grab their left chopsticks simultaneously,
All the element of chopstick will be 0
When each philosopher tries to grab her right chopstick, she will be delayed forever
Need some remedies against the deadlock
7.5 The Dining-Philosophers Problem
교착상태 문제의 해결책 동시에 테이블에 앉을 수 있는 철학자 수는 4 로 한다 . 철학자는 두개의 젓가락을 모두 잡을 수 있는 경우에만
잡는것을 허용한다 . 비동기식 해결 :
홀수번째 철학자는 왼쪽을 먼저 집고 오른쪽을 집도록 한다 . 짝수 번째 철학자는 오른쪽을 먼저 잡고 왼쪽을 잡도록 한다 .
Any satisfactory solution must guard against the possibility of starvation. A deadlock-free solution does not necessarily eliminate the possibility of starvation
7.6 임계영역 (Critical Regions)
Various difficulties (Semaphore) (Suppose) A process interchanges the order
signal(mutex);…
critical section…
wait(mutex);
mutual-exclusion 요구사항을 위반 항상 재현가능한 상황이 아님
7.6 Critical Regions
(Suppose) replaces signal(mutex) with wait(mutex)
wait(mutex);…
critical section….
wait(mutex)
Deadlock will occur
(Suppose) process omits the wait(mutex), or the signal(mutex), or both 상호배제 (Mutual exclusion) 위반 교착상태 (deadlock) 발생
7.6 Critical Regions
Fundamental high level synchronization construct Critical region(conditional critical region) Monitor
Critical region Encapsulation
프로세스가 다른 프로세스의 지역 데이터에 직접 접근하지 못함 그러나 프로세스는 전역 데이터를 공유할 수 있음 .
Variable v of type T 다음과 같이 선언
– v : shared T; 변수 v 는 region 내에서만 접근 가능
– region v when B do S;• expression B : Boolean expression• When a process tries the enter the critical-section region,B is evaluated
7.6 Critical Regions
Distinct sequential processes( 별개의 순차 프로세스 )region v when (true) S1;
region v when (true) S2; “S1 followed by S2” or “S2 followed by S1”
Let us code the bounded-buffer scheme The buffer space and its pointers are encapsulated in
struct buffer {
item pool[n] ;
int count, in, out ;
};
7.6 Critical Regions The producer process
region buffer when (count < n) {
pool[in] = nextp ;
in = (in+1) % n;
count++;
}
The consumer processregion buffer when (count > 0) {
nextc = pool[out]
out = (out +1) mod n;
count--;
end;
7.6 Critical Regions
How the conditional critical region could be Implemented by a compiler
shared variable
semaphore mutex, first_delay, second_delay ;
int first_count, second_count
7.6 Critical Regionswait(mutex);while ( !B ) {
first_count++;if (second_count > 0)
signal(second_delay)
else signal(mutex);wait(first_delay);first_count--;second_count++;if (first_count > 0)
signal(first_delay)else signal(second
_delay);wait(second_delay);second-count --;
}S;if (first_count) > 0
signal(first_delay);else if (second_count )> 0
signal(second_delay);
else signal(mutex);
region x when (B) S;
Implementation of the conditional-region construct
7.7 Monitors
Monitor Characterized by a set of programmer-defined operators
The syntax of a monitor Monitor Structure
monitor monitor-name{ shared variable declarations
procedure body P1( … ) { …
}
prodedure body P2( … { …
}..
. .
procedure body P1( … ) { …
}
{ initialization code}
7.7 Monitors
Monitor type cannot be used directly by the various processes.
Monitor construct Only one process at a time can be active within the monitor Programmer
Don’t need to code the synchronization
공유 데이터
초기화코드
연산들
진입 큐
조건변수를 갖는 모니터
7.7 Monitors
Variable and operation condition x,y ;
Operation x.wait();
– suspend x.signal();
– resume
Example Two processes P and Q When the x.signal operation is invoked by a process P, there is
a suspended process Q associated with condition x. If the suspended process Q is allowed to resume its execution,
the signaling process P must wait.
P : active(x.signal)
Q suspended
Q Resume
PWait
7.7 Monitors
Process-resumption FCFS ordering
The longest is resumed first Too simple
Conditional-wait x.wait( c ); c : priority number The smallest associated priority number is resumed next
Example Controls the allocation of a single resource among competing
processes.
7.7 Monitors A monitor to allocate a single resource
monitor dp{ enum { thinking, hungry, eating} state[5]; condition self[5];
void pickup (int i) { state[i] = hungry; test(i); if ( state[i] != eating) self[i].wait();}
void putdown (int i) { state[i] = thinking; 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 init() { for (int i = 0; i < 5; i++) state[i] = thinking; }}
7.7 Monitors Sequence
R.acquire(t);
…
access the resource;
...
R.release;
(R is an instance of type resource-allocation)
The monitor concept cannot guarantee that the preceding access sequences will be observed
Access the resouce without gaining access permission to that resource
Never release the resource once it has been granted access to that resource
Attempt to release a resource that it never requested Request the same resource twice
( without first releasing that resource)