do{
entry section
critical section
exit section
remainder section
} while(1);
int turn;
initially turn = 0; → Pi can enter its critical section if (turn == i)
do{
while (turn != 0); /* My turn? */ -> 내 차례가 아닐 때에는 while문 돌면서 대기
critical section
turn = 1; /* Now it's your turn */
remainder section
} while (1);
do{
while (turn != 1); /* My turn? */
critical section
turn = 0; /* Now it's your turn */
remainder section
} while (0);
boolean flag[2];
initially flag[모두] = false; /* no one is in CS */
Pi ready to enter its critical section if (flag[i] == true)
do{
flag[i] = true; /* Pretend I am in */
while (flag[j]); /* Is he also in? then wait */
critical section
flag[i] = false; /* I am out now */
remainder section
} while (1);
do{
flag[i] = true; /* My intention is to enter ...*/
turn = j; /* Set to his turn */
while (flag[j] && turn == j); /* wait only if ... */
critical section
flag[i] = false;
remainder section
} while (1);
Synchronization variable;
boolean lock = false;
Process Pi
do{
while(Test_and_Set(lock));
critical section
lock = false;
remainder section
}
P(S): while(S<=0) do no-op; -> wait
S--;
If positice, decrement-&-enterV(S):
S++;
Synchronization variable
semaphore mutex; /* initially 1: 1rork CS에 들어갈 수 있으 */
Process Pi
do{
P(mutex); /* If positive, dec-&-enter, Otherwise, wait */
critical section
V(mutex); /* Increment semaphore */
remainder section
} while (1);
typedef struct
{ int value; /* semaphore */
struct process *L /*process wait queue */
} semaphore;
P(S): S.value--; /* prepare to enter */
If (S.value < 0) /* negative, I cannot enter */
{ add this process to S.L;
block();
}
V(S): S.value++;
If (S.value <= 0) {
remove a process P from S.L;
wakeup(P);
}
readcount; /* 현재 DB에 접근 중인 Reader의 수 */
mutex /* 공유 변수 readcount를 접근하는 코드(critical section)의 mutual exclusion 보장을 위해 사용 */
db /* Reader와 writer가 공유 DB 자체를 올바르게 접근하게 하는 역할 */
Semaphore의 문제점
ex.
동시 수행중인 프로세스 사이에서 abstract data type의 안전한 공유를 보장하기 위한 high-level synchronization construct
monitor monitor-name
{ shared variable declarations
procedure body P1 (...) {
...
}
procedure body P2 (...) {
...
}
procedure body Pn (...) {
...
}
{
initialization code
}
}
condition x, y;
x.wait();
x.signal();
monitor bounded buffer
{ int buffer[N];
condition full, empty;
/* condition var.은 값을 가지지않고 자신의 큐에 프로세스를 매달아서 sleep 시키거나 큐에서 프로세스를 깨우는 역할만 함 */
void produce (int x)
{ if there is no empty buffer
empty.wait();
add x to an empty buffer
full.signal();
}
void consume (int *×)
{ if there is no full buffer
full.wait();
remove an item from buffer and store it to *x
empty.signal();
}
}
참고자료
KOCW, 반효경 교수님, 운영체제
잘 봤습니다. 좋은 글 감사합니다.