77
신신신신신 신신신신신신 - 신신신신 1 Lecture #5 Lecture #5 Concurrency: Mutual Concurrency: Mutual Exclusion and Exclusion and Synchronization Synchronization ( ( 신신신신신 신신신 신신신신신 신신신 ) )

Lecture #5

  • Upload
    ash

  • View
    119

  • Download
    0

Embed Size (px)

DESCRIPTION

Lecture #5. Concurrency: Mutual Exclusion and Synchronization (상호배제와 동기화). 프로그램 실행 ( Program Execution). 프로그램은 프로세스의 집합으로 이루어진다 프로그램 실행( Program Execution) 순차 실행 (Sequential Execution) 병행 실행( Concurrent Execution) 병렬 실행( Parallel Execution) 병행성(동시성: Concurrency) > 병렬성( Parallelism). - PowerPoint PPT Presentation

Citation preview

Page 1: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제1

Lecture #5Lecture #5

Concurrency: Mutual Concurrency: Mutual Exclusion and Exclusion and

SynchronizationSynchronization

(( 상호배제와 동기화상호배제와 동기화 ))

Page 2: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제2

프로그램 실행 프로그램 실행 ((Program Execution)Program Execution)

프로그램은 프로세스의 집합으로 이루어진다 프로그램 실행 (Program Execution)

순차 실행 (Sequential Execution) 병행 실행 (Concurrent Execution) 병렬 실행 (Parallel Execution) 병행성 ( 동시성 :Concurrency) > 병렬성 (Parallelism)

Page 3: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제3

병렬 실행병렬 실행 ((Concurrent Execution)Concurrent Execution) 의 의 문제점문제점

병행 프로세스들 (Concurrent processes (or threads)) 는 일반적으로 데이터와 자원을 공유한다

만약 공유 데이터에 대한 접근을 적절하게 제어하지 않으면 일부 프로세스는 잘못된 데이터를 접근하게 된다

병행 프로세스의 실행 결과는 병행 프로세스 간의 실행이 섞이는 순서에 의하여 결정되어 진다

Page 4: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제4

공유 데이터 접근의 예공유 데이터 접근의 예

3 variables: A, B, C which are shared by thread T1 and thread T2

T1 computes C = A+B

T2 transfers amount X from A to B T2 must do: A = A -X and B = B+X (so that A+B is

unchanged)

But if T1 computes A+B after T2 has done A = A-X but before B = B+X then T1 will not obtain the correct result for C = A + B

The resource sharing requires the synchronization between threads

Page 5: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제5

병행 실행의 예병행 실행의 예 (1)(1)

생산자 & 소비자 프로세스

생산자 프로세스

(Producer Process)

소비자 프로세스

(Consumer Process)

1

2

3

4…

n

n-1

in out

Page 6: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제6

병행 실행의 예병행 실행의 예 (2)(2)

생산자 프로세스 코드

repeat

. . .

nextp 에서 한 항목을 생산

. . .

while count == n do no-op;

buffer[in] = nextp;

in = (in + 1) mod n;

count = count + 1;

until FALSE;

소비자 프로세스 코드

repeat

while count == 0 do no-op;

nextc = buffer[out];

out = (out + 1) mod n;

count = count - 1;

. . .

nextc 에서 한 항목을 소비

. . .

until FALSE;

Page 7: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제7

병행 실행의 예병행 실행의 예 (3)(3)

생산자 프로세스 코드

count = count + 1;

register1 = count

register1 = register1 + 1

count = register1

소비자 프로세스 코드

count = count - 1;

register2 = count

register2 = register2 - 1

count = register2

Page 8: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제8

병행 실행의 예병행 실행의 예 (4)(4)

생산자 프로세스와 소비자 프로세스가 병행 실행되는 경우 :

T0: 생산자 register1 = count {register1 = 5}T1: 생산자 register1 = register1+1 {register1 = 6}T2: 소비자 register2 = count {register2 = 5}T3: 소비자 register2 = register2-1 {register2 = 4}T4: 소비자 count = register2 {count = 4}T5: 생산자 count = register1 {count = 6}

문제점 : 두 개의 프로세스가 동시에 count 변수에 접근 해결책 : count 변수에 접근하는 순서를 제어 , 즉

한번에 하나의 프로세스만이 count 변수에 접근하도록 제어

프로세스 동기화 (Process Synchronization) 가 필요

Page 9: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제9

병렬 실행에서의 자원 공유병렬 실행에서의 자원 공유

병행 실행에서의 자원 공유에 따른 문제점1. 상호 배제 (Mutual Exclusion)

병행 프로세스들이 공유 자원을 동시에 접근함으로써 전혀 예기치 못하는 결과가 발생할 수 있다

한 시점에 공유 자원을 접근하는 실행 단위 ( 프로세스 또는 쓰레드 ) 는 단지 하나만 존재하여야 한다

2. 실행 동기화 (Execution Synchronization)

하나의 프로그램은 구성하는 병행 프로세스들은 상호간에 일련의 실행 순서에 맞추어 실행되어야 한다

예 : 생산자 - 소비자 모델에서 생산자가 버퍼에 데이터를 저장하여야 소비자가 데이터 처리가 가능해진다

Page 10: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제10

임계구역임계구역 ((critical section) critical section) 문제문제 (1)(1)

임계구역 (Critical Section: CS) 하나의 프로세스가 공유 데이터를 접근하는 코드를 실행할

때에 그 프로세스가 임계구역에 있다라고 정의

상호 배제 (Mutual Exclusion) The execution of critical sections must be mutually

exclusive 다중 프로세서 환경에서도 임계구역에서 실행하고 있는

프로세스는 오직 하나만 있어야 한다

상호 배제에 대한 접근법 병행 실행되는 각 프로세스는 임계구역에 들어가기 위해서는

임계구역 실행에 대한 허용 (permission) 을 얻어야 한다

Page 11: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제11

임계구역임계구역 ((critical section) critical section) 문제문제 (2)(2)

임계 구역 (critical section) 문제 프로세스 동기화 프로토콜을 설계 병행 프로세스의 실행 결과가 실행 순서에 상관없이

일정하도록 프로세스 상호간에 협조하는 프로토콜을 설계

Page 12: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제12

임계 구역 문제의 기본 가정임계 구역 문제의 기본 가정 (1)(1)

병행 프로세스의 전형적인 구조 진입 구역 (entry section)

임계 구역에 진입하기 위해 허용을 요구하는 코드 영역 출구 구역 (exit section)

임계 구역 다음에 나오는 영역으로 임계 구역을 벗어나기 위한 코드 영역

잔류 구역 (remainder section) 프로그램의 나머지 코드 영역

Page 13: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제13

임계 구역 문제의 기본 가정임계 구역 문제의 기본 가정 (2)(2)

Repeat

entry section

critical section exit section remainder section

until FALSE

병행 프로세스의 전형적인 구조 ( 계속 )

Page 14: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제14

임계 구역 문제의 기본 가정임계 구역 문제의 기본 가정 (3)(3)

각 프로세스는 0 이 아닌 속도로 실행된다 n 개의 프로세스의 상대적인 실행 속도에 대한

가정은 없다 n 개의 프로세스의 실행순서에 대한 가정은 없다 많은 CPU 가 존재할 수 있다 동일한 메모리 영역을 동시에 접근할 수 없도록

제어하는 메모리 하드웨어가 있다 임계 구역 문제에 대한 해결책을 찾는 것은 진입

구역과 출구 구역의 코드를 정의하는 것이다

Page 15: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제15

임계 구역 문제의 해결책에 대한임계 구역 문제의 해결책에 대한 세 가지 요구조건 세 가지 요구조건 ((

1) 1) 상호배제 (Mutual Exclusion)

항상 최대한 하나의 프로세스만이 임계구역에서 실행할 수 있다

한 프로세스가 임계구역에 있으면 다른 프로세스는 임계구역에 진입할 수 없다

진행 (Progress) 임계구역에 있는 프로세스가 없고 다른 프로세스들이 임계

구역 진입을 요구할 때에 단지 잔류 구역에서 실행되고 있지 않은 프로세스 만이 임계 구역에 진입할 수 있다

임계 구역 진입 프로세스 선택은 무기한 연기될 수 없다 Deadlock Avoidance

Page 16: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제16

임계 구역 문제의 해결책에 대한임계 구역 문제의 해결책에 대한 세 가지 요구조건 세 가지 요구조건 ((

2)2) 한계 대기 (Bounded Waiting)

하나의 프로세스가 임계 구역 진입을 요청한 후에 진입이 허용될 때까지 다른 프로세스가 임계 구역을 진입하는 회수 (시간 ) 에 한계를 두어야 한다

그렇지 않으면 진입 요청한 프로세스는 기아상태 (starvation) 가 될 수 있다

Page 17: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제17

임계 구역 문제 해결책의 분류임계 구역 문제 해결책의 분류

소프트웨어 해결책 (Software solutions) software algorithms who’s correctness does not rely

on any other assumptions

하드웨어 해결책 (Hardware solutions) rely on some special machine instructions

운영체제 해결책 (Operation System solutions) OS provide some functions and data structures to the

programmer

Page 18: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제18

소프트웨어 해결책소프트웨어 해결책

2 개의 프로세스를 위한 해결책 Algorithm 1 and 2 are incorrect Algorithm 3 is correct (Peterson’s algorithm)

n 개의 프로세스를 위한 해결책 the bakery algorithm

Notation 2 processes: P0 and P1 When presenting processes, Pi, Pj always denote the other

processes (i != j)

Page 19: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제19

Algorithm 1Algorithm 1

The shared variable turn is initialized (to 0 or 1) before executing any Pi

Pi’s critical section is executed iff turn = i

Pi is busy waiting if Pj is in CS: mutual exclusion is satisfied

Progress requirement is not satisfied

Process Pi:repeat while(turn!=i){}; CS turn:=j; RSuntil FALSE

Ex: P0 has a large RS and P1 has a small RS. If turn=0, P0 enter its CS and then its long RS (turn=1). P1 enter its CS and then its RS (turn=0) and tries again to enter its CS: request refused! He has to wait that P0 leaves its RS.

Page 20: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제20

Algorithm 2Algorithm 2

Keep one BOOL variable for each process: flag[0] and flag[1]

Pi signals that it is ready to enter it’s CS by: flag[i]:=true

Mutual Exclusion is satisfied but not the progress requirement

If we have the sequence: T0: flag[0]:=true T1: flag[1]:=true

Both process will wait forever to enter their CS: we have a deadlock

Process Pi:repeat flag[i]:=true; while(flag[j]){}; CS flag[i]:=false; RSuntil FALSE

Page 21: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제21

Algorithm 3 (Peterson’s algorithm)Algorithm 3 (Peterson’s algorithm)

Initialization: flag[0]:=flag[1]:=false

turn := 0 or 1 Willingness to enter CS is

specified by flag[i]:=true If both processes attempt

to enter their CS simultaneously, only one turn value will last

Exit section: specifies that Pi is unwilling to enter CS

Process Pi:repeat flag[i]:=true; turn:=j; do {} while (flag[j]and turn=j); CS flag[i]:=false; RSuntil FALSE

Page 22: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제22

Algorithm 3: proof of correctness(1)Algorithm 3: proof of correctness(1)

Mutual exclusion is preserved since: P0 and P1 are both in CS only if flag[0] = flag[1] = true

and only if turn = i for each Pi (impossible)

The progress and bounded waiting requirements are satisfied: Pi cannot enter CS only if stuck in while() with condition

flag[ j] = true and turn = j. If Pj is not ready to enter CS then flag[ j] = false and Pi

can then enter its CS

Page 23: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제23

Algorithm 3: proof of correctness(2)Algorithm 3: proof of correctness(2)

If Pj has set flag[ j]=true and is in its while(), then either turn=i or turn=j

If turn=i, then Pi enters CS. If turn=j then Pj enters CS but will then reset flag[ j]=false on exit: allowing Pi to enter CS

but if Pj has time to reset flag[ j]=true, it must also set turn=i

since Pi does not change value of turn while stuck in while(), Pi will enter CS after at most one CS entry by Pj (bounded waiting)

Page 24: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제24

n-process solution: n-process solution: The bakery algorithm (1)The bakery algorithm (1)

Before entering their CS, each Pi receives a number. Holder of smallest number enter CS

(like in bakeries, ice-cream stores...) When Pi and Pj receives the same number:

if I < j then Pi is served first, else Pj is served first

Pi resets its number to 0 in the exit section Notation:

(a, b) < (c, d) if a < c or if a = c and b < d max(a0,…,ak) is a number b such that b >= ai for i=0,..k

Page 25: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제25

The bakery algorithm (2)The bakery algorithm (2)

Shared data: choosing: array[0..n-1] of boolean;

initialized to false number: array[0..n-1] of integer;

initialized to 0

Correctness relies on the following fact: If Pi is in CS and Pk has already chosen its number[k]!= 0, then

(number[i], i) < (number[k], k)

Page 26: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제26

The bakery algorithm (3)The bakery algorithm (3)

Process Pi:repeat choosing[i]:=true; number[i]:=max(number[0]..number[n-1])+1; choosing[i]:=false; for j:=0 to n-1 do { while (choosing[j]) {}; while (number[j]!=0 and (number[j],j)<(number[i],i)){}; } CS number[i]:=0; RSuntil FALSE

Page 27: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제27

소프트웨어 해결책의 단점소프트웨어 해결책의 단점

임계 구역에 진입하기를 원하는 프로세스는 busy waiting 한다 필요 없이 CPU 시간을 낭비한다

임계 구역이 긴 경우에는 임계 구역 진입을 기다리는 프로세스를 대기 상태로 전환하는 것 ( blocking) 이 효과적이다

Page 28: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제28

하드웨어 해결책하드웨어 해결책 : : interrupt disablinginterrupt disabling

On a uniprocessor: mutual exclusion is preserved but efficiency of execution is degraded while in CS, we cannot

interleave execution with other processes that are in RS

On a multiprocessor: mutual exclusion is not preserved

Generally not an acceptable solution

Process Pi:repeat disable interrupts critical section enable interrupts remainder sectionuntil FALSE

Page 29: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제29

하드웨어 해결책하드웨어 해결책 : : special machine instructionsspecial machine instructions

일반적으로 하나의 메모리 영역에 대한 접근은 배타적이다 하나의 메모리에 대해 동시에 여러 개의 접근이 이루어질 수

없다

명령어 확장 : 같은 메모리 영역에 2 가지의 동작을 원자적으로 (atomically) 실행하는 명령어 제공 예 - reading and writing a memory location

test-and-set, xchg(swap) instructions The execution of such an instruction is mutually

exclusive (even with multiple CPUs) 상호배제 문제를 해결하기 위해 이용

Page 30: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제30

test-and-set instruction(1)test-and-set instruction(1)

A C++ description of test-and-set instruction:

bool testset(int& i){ if (i==0) { i=1; return true; } else { return false; }}

Page 31: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제31

test-and-set instruction(2)test-and-set instruction(2)

An algorithm that uses testset instruction for Mutual Exclusion: Shared variable b is

initialized to 0 Only the first Pi who sets b

enter CS

Process Pi:repeat repeat{} until testset(b); CS b:=0; RSuntil FALSE

Page 32: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제32

test-and-set instruction (3)test-and-set instruction (3)

Mutual exclusion is preserved if Pi enter CS, the other Pj are busy waiting

Problem: still using busy waiting When Pi exit CS, the selection of the Pj who will

enter CS is arbitrary: no bounded waiting Hence starvation is possible

Page 33: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제33

xchg instructionxchg instruction

Processors (ex: Pentium) often provide an atomic xchg(a,b) instruction that swaps the content of a and b.

void xchg(int a, int b){

int temp;

temp = a; a = b; b = temp;}

xchg(a,b) suffers from the same drawbacks as test-and-set instruction

Page 34: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제34

Using xchg for mutual exclusionUsing xchg for mutual exclusion

Shared variable b is initialized to 0

Each Pi has a local variable k

The only Pi that can enter CS is the one who finds b=0

This Pi excludes all the other Pj by setting b to 1

Process Pi:repeat k:=1 repeat xchg(k,b) until k=0; CS b:=0; RSuntil FALSE

Page 35: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제35

운영체제 해결책운영체제 해결책

운영체제는 프로세스 동기화를 위한 도구를 제공 세마포어 (Semaphores) 모니터 (Monitors) 메시지 전송 (Message Passing)

Page 36: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제36

세마포어세마포어 ((Semaphores) (1)Semaphores) (1)

정의 definition Busy waiting 을 요구하지 않는 Synchronization tool

(provided by the OS) 운영체제가 제공하는 하나의 자원 세마포어 S 는 다음의 2 atomic and mutually exclusive

operations 에 의해서만 접근할 수 있는 정수 wait(S) signal(S)

Busy waiting avoidance when a process has to wait, it will be put in a blocked

queue of processes waiting for the same event

Page 37: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제37

세마포어세마포어 ((Semaphores) (2)Semaphores) (2)

A semaphore is a record (structure):

type semaphore = record count: integer; queue: list of process end;var S: semaphore;

wait 연산에서 프로세스가 세마포어 S 을 기다려야 할 때에는 대기 상태로 전환되어 세마포어 큐에 들어간다

signal 연산은 세마포어 큐로부터 하나의 프로세스를 꺼내어 준비 큐에 저장한다

Page 38: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제38

세마포어 연산 세마포어 연산 ((atomic)atomic)

wait(S): S.count--; if (S.count<0) { block this process place this process in S.queue }

signal(S): S.count++; if (S.count<=0) { remove a process P from S.queue place this process P on ready list }

S.count must be initialized to a nonnegative value (depending on application)

Page 39: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제39

Semaphores: observations (1)Semaphores: observations (1)

S.count >=0 일 때 the number of processes that can execute wait(S)

without being blocked = S.count S.count<0 일 때

the number of processes waiting on S = |S.count| Atomicity and mutual exclusion

no 2 process can be in wait(S) and signal(S) (on the same S) at the same time (even with multiple CPUs)

The blocks of code defining wait(S) and signal(S) are critical sections

Page 40: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제40

Semaphores: observations (2)Semaphores: observations (2)

The critical sections defined by wait(S) and signal(S) are very short typically 10 instructions

Solutions: uniprocessor: disable interrupts during these operations

(i.e: for a very short period) This does not work on a multiprocessor machine

multiprocessor: use previous software or hardware schemes

The amount of busy waiting should be small.

Page 41: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제41

Using semaphores for solving critical Using semaphores for solving critical section problems section problems

n 개의 프로세스에 적용 S.count 을 1 로 초기화 단지 하나의 프로세스만 CS

진입이 허용된다 (mutual exclusion)

S.count 을 k 로 초기화하면 k 개의 프로세스가 CS 에 진입할 수 있다

Process Pi:repeat wait(S); CS signal(S); RSuntil FALSE

Page 42: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제42

Using semaphores to synchronize Using semaphores to synchronize processesprocesses

We have 2 processes: P1 and P2

Statement S1 in P1 needs to be performed before statement S2 in P2

Then define a semaphore ‘synch’

Initialize ‘synch’ to 0

Proper synchronization is achieved by having in P1: S1;

signal(synch);

And having in P2: wait(synch); S2;

Page 43: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제43

생산자생산자 // 소비자 문제소비자 문제((producer/consumer problem)producer/consumer problem)

A producer process produces information that is consumed by a consumer process 예 : a print program produces characters that are

consumed by a printer 생성된 정보를 사용할 때까지 저장할 buffer 가

필요하다 A common paradigm for cooperating processes

Page 44: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제44

P/C ProblemP/C Problem: : unbounded buffer(1)unbounded buffer(1)

1 차원 배열로 구성된 무한 버퍼 (unbounded buffer) 을 가지는 경우

in 은 다음에 생성된 정보를 저장할 위치를 지정 Out 은 다음에 소비될 저장하고 있는 위치를 지정

Page 45: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제45

P/C ProblemP/C Problem: : unbounded buffer(2)unbounded buffer(2)

semaphore S : to perform mutual exclusion on the buffer only 1 process at a time can access the buffer

semaphore N : to synchronize producer and consumer on the number N (= in - out) of items in the buffer an item can be consumed only after it has been

created

Page 46: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제46

P/C ProblemP/C Problem: : unbounded buffer(3)unbounded buffer(3)

생산자는 항상 자유롭게 생성된 정보를 버퍼에 추가할 수 있다 버퍼에 저장하기 전에 wait(S) 버퍼에 저장한 후에 signal(S)

생산자는 버퍼에 새로운 정보를 추가한 후에 새로운 정보가 생성되었음을 동기화 하기 위해 signal(N) 수행

소비자는 먼저 소비할 정보가 있는지를 검사하기 위해 wait(N) 을 수행하고 , 정보가 버퍼에 있으면 버퍼를 접근하기 위해 wait(S)/signal(S) 을 수행

Page 47: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제47

P/C ProblemP/C Problem: : unbounded buffer(4)unbounded buffer(4)- Solution- Solution

Initialization: S.count:=1; N.count:=0; in:=out:=0;

append(v): b[in]:=v; in++;

take(): w:=b[out]; out++; return w;

Page 48: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제48

P/C ProblemP/C Problem: : unbounded buffer(5)unbounded buffer(5)- Solution- Solution

Producer:repeat produce v; wait(S); append(v); signal(S); signal(N);until FALSE

Consumer:repeat wait(N); wait(S); w:=take(); signal(S); consume(w);until FALSE

critical sections

Page 49: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제49

P/C ProblemP/C Problem: : unbounded buffer(6)unbounded buffer(6)

Remarks: The consumer must perform wait(N) before wait(S),

otherwise deadlock occurs if consumer enter CS while the buffer is empty

Page 50: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제50

P/C Problem: finite circular buffer(1)P/C Problem: finite circular buffer(1)

저장된 정보의 수인 N 이 최소한 1 이상일 때에 소비자가 버퍼 접근이 가능하다 (ie. N != in – out)

생산자는 버퍼의 빈 공간의 수 E 가 1 이상일 때에 버퍼에 정보를 저장할 수 있다

Page 51: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제51

P/C Problem: finite circular buffer(2)P/C Problem: finite circular buffer(2)

필요한 세마포어 : semaphore S : to have mutual exclusion on buffer access semaphore N : to synchronize producer and consumer

on the number of consumable items semaphore E : to synchronize producer and consumer

on the number of empty spaces

Page 52: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제52

P/C Problem: finite circular buffer(3)P/C Problem: finite circular buffer(3)- Solution- SolutionInitialization: S.count:=1; in:=0; N.count:=0; out:=0; E.count:=k;

Producer:repeat produce v; wait(E); wait(S); append(v); signal(S); signal(N);until FALSE

Consumer:repeat wait(N); wait(S); w:=take(); signal(S); signal(E); consume(w);until FALSE

critical sections

append(v):b[in]:=v;in:=(in+1) mod k;

take():w:=b[out];out:=(out+1) mod k;return w;

Page 53: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제53

The Dining Philosophers Problem(1)The Dining Philosophers Problem(1)

5 philosophers who only eat and think

each need to use 2 forks for eating

we have only 5 forks A classical synchronization

problem Illustrates the difficulty of

allocating resources among process without deadlock and starvation

Page 54: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제54

The Dining Philosophers Problem(2)The Dining Philosophers Problem(2)

Each philosopher is a process

One semaphore per fork: fork: array[0..4] of

semaphores Initialization:

fork[i].count:=1 for i:=0..4 A first attempt Deadlock if each

philosopher start by picking his left fork!

Process Pi:repeat think; wait(fork[i]); wait(fork[i+1 mod 5]); eat; signal(fork[i+1 mod 5]); signal(fork[i]); forever

Page 55: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제55

The Dining Philosophers Problem(3)The Dining Philosophers Problem(3)

A solution: admit only 4 philosophers at a time that tries to eat

Then 1 philosopher can always eat when the other 3 are holding 1 fork

Hence, we can use another semaphore T that would limit at 4 the number of philosophers “sitting at the table”

Initialize: T.count:=4

Process Pi:repeat think; wait(T); wait(fork[i]); wait(fork[i+1 mod 5]); eat; signal(fork[i+1 mod 5]); signal(fork[i]); signal(T); forever

Page 56: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제56

이진 세마포어 이진 세마포어 ((Binary semaphores) (1)Binary semaphores) (1)

계수 세마포어 (counting (or integer) semaphores) 이진 세마포어 (binary semaphores)

counting semaphores 와 유사하나 “ count” 가 Boolean 값 (0 또는 1) 을 가진다

일반적으로 counting semaphores 보다 사용하기 어렵다 예 : k > 1 인 값으로 초기화하기 힘들다

Page 57: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제57

이진 세마포어이진 세마포어((Binary semaphores)(2)Binary semaphores)(2)waitB(S): if (S.value = 1) { S.value := 0; } else { block this process place this process in S.queue }

signalB(S): if (S.queue is empty) { S.value := 1; } else { remove a process P from S.queue place this process P on ready list }

Page 58: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제58

SpinlocksSpinlocks

They are counting semaphores that use busy waiting (instead of blocking)

Useful on multi processors when critical sections last for a short time

We then waste a bit of CPU time but we save process switch

wait(S): S--; while S<0 do{};

signal(S): S++;

Page 59: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제59

세마포어의 문제점세마포어의 문제점

세마포어는 상호배제 (mutual exclusion) 과 프로세스 동기화에 유용한 도구

wait(S) 와 signal(S) 가 여러 프로세스 사이에 분산될 수 있어 전체적인 동작을 이해하는데 어렵다

모든 프로세스에서 세마포어를 정상적으로 사용하여야 한다 하나의 프로세스에서 세마포어 사용에 오류가 발생하면 전체

프로세스가 실패할 수 있다

Page 60: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제60

모니터모니터 ((Monitors) (1)Monitors) (1)

고급 프로그래밍 언어에서 제공하는 동기화 구조 (Synchronization Construct) 세마포어와 동일한 기능을 제공 보다 쉬운 제어 기능을 제공

많은 병행 프로그래밍 언어 (Concurrent Programming Language) 에서 지원 Concurrent Pascal, Modula-3, uC++, Java...

Page 61: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제61

모니터모니터 ((Monitors) (2)Monitors) (2)

다음 항목을 포함하는 소프트웨어 모듈 : 지역 변수 하나 이상의 프로시듀어 (procedures) 초기화 코드 (initialization sequence)

모듈 구성 type monitor-name = monitor

local variable declarations

procedure entry P1(…)

begin … end;

procedure entry P2(…)

begin … end;

procedure entry Pn(…)

begin … end;

begin

initialization code

end

Page 62: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제62

모니터모니터 ((Monitors) (3)Monitors) (3)

모니터 동작 특징 : 지역 변수는 모니터 내의 프로시저에 의해서만 접근할 수 있다 프로세스는 모니터의 프로시저 호출을 통해 모니터에 진입할

수 있다 언제나 단지 하나의 프로세스만이 모니터 안에 있을 수 있다

모니터는 상호배제 (mutual exclusion) 를 보장한다 프로그래머가 상호배제를 위하여 별도의 프로그램을 작성할

필요가 없다 공유 데이터 또는 자원을 모니터 안에 둠으로써 보호할 수

있다 공유 자원을 지역 변수로 정의

Page 63: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제63

조건 변수조건 변수 ((Condition variables)Condition variables)

하나의 프로세스가 모니터 내에서 실행되기 전에 기다려야 하는 조건을 나타내는 변수 병행 처리에서의 동기화 도구

단지 모니터 내에서만 접근 가능하다 다음의 두개의 연산에 의해서만 접근 및 수정이

가능하다 cwait(a): 조건 변수 a 에 대해 호출한 함수를 대기 상태로

전환한다 csignal(a): 조건 변수 a 에 대해 대기 상태인 프로세스 중

하나의 프로세스를 선택하여 실행을 재개한다 프로그래머에 의해 프로세스 동기화에 이용된다

Page 64: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제64

모니터의 동작모니터의 동작

대기 프로세스는 진입 큐 또는 조건 변수 큐에서 대기한다

하나의 프로세스가 cwait(cn) 을 호출하여 조건 변수 cn 의 큐에서 대기하게 된다

csignal(cn) 은 모니터가 조건 변수 cn 의 큐에서 하나의 프로세스을 가져와 실행하게 한다

csignal(cn) 을 호출한 프로세스는 실행을 중단하고 urgent queue 에서 대기한다

Page 65: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제65

생산자생산자 // 소비자 프로세스 문제소비자 프로세스 문제 (1)(1)

Two types of processes: producers consumers

Synchronization is now confined within the monitor

append(.) and take(.) are procedures within the monitor The procedures are the only

means by which P/C processes can access the buffer

If these procedures are correct, synchronization will be correct for all participating processes

Producer_I:repeat produce v; Append(v);until FALSE

Consumer_I:repeat Take(v); consume v;until FALSE

Page 66: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제66

생산자생산자 // 소비자 프로세스 문제소비자 프로세스 문제 (2)(2)

버퍼를 공유하기 위해 모니터 (Monitor) 가 필요 buffer: array[0..k-1] of items;

두개의 조건 변수 : notfull: csignal(notfull) 는 버퍼가 차지 않았음을 나타낸다 notempty: csignal(notempty) 는 버퍼가 비어 있지 않음을

나타낸다 버퍼 조작을 위한 포인터와 카운터 :

nextin: 다음 항목을 저장할 위치 포인터 nextout: 다음 항목을 가져올 위치 포인터 count: 현재 버퍼에 저장된 항목의 수

Page 67: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제67

생산자생산자 // 소비자 프로세스 문제소비자 프로세스 문제 (3)(3)

Monitor boundedbuffer: buffer: array[0..k-1] of items; nextin:=0, nextout:=0, count:=0: integer; notfull, notempty: condition;

Append(v): if (count=k) cwait(notfull); buffer[nextin]:= v; nextin:= nextin+1 mod k; count++; csignal(notempty);

Take(v): if (count=0) cwait(notempty); v:= buffer[nextout]; nextout:= nextout+1 mod k; count--; csignal(notfull);

Page 68: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제68

메시지 전송메시지 전송 ((Message Passing)Message Passing)

프로세스간의 통신 (interprocess communication : IPC) 을 위한 일반적인 방법 : 하나의 컴퓨터 내의 프로세스간 통신 분산 시스템 내의 프로세스간 통신

프로세스 동기화 및 상호배제 문제를 위한 방법으로 이용

두개의 기본적인 연산 : send(destination, message) receive(source, message) 위의 연산에서 프로세스는 대기상태로 전환될 수도 있고

안될 수도 있다

Page 69: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제69

메시지 전송을 통한 동기화 메시지 전송을 통한 동기화 (1)(1)

송신측 : 일반적으로 send(.,.) 호출한 다음에 실행을 계속한다 (non-blocking) 다수의 수신자에게 메시지 전송이 가능하다 보통 수신자가 메시지 수신 여부를 알려 주기를 기대한다

수신측 : 일반적으로 receive(.,.) 호출한 다음에 메시지가 수신될 때까지 대기상태가 된다 (blocking) 보통 수신자는 실행을 계속하기 위해 정보를 요구한다 -

정보가 전송될 때까지 기다린다 송신자가 메시지를 전송 전에 실패한다면 수신자는 무한정

기다리게 된다

Page 70: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제70

메시지 전송을 통한 동기화 메시지 전송을 통한 동기화 (2)(2)

다른 가능성을 제공된다 예 : blocking send, blocking receive:

both are blocked until the message is received occurs when the communication link is unbuffered (no

message queue) provides tight synchronization (rendez-vous)

Page 71: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제71

메시지 전송에서의 주소 지정메시지 전송에서의 주소 지정

직접 주소 지정 (direct addressing): 메시지 전송 연산에서 송신자 / 수신자를 위해 특정 프로세스

ID 를 사용한다

간접 주소 지정 (indirect addressing): 메시지는 메시지 큐로 구성된 mailbox 로 전송된다 송신자는 mailbox 로 메시지를 보내고 , 수신자는 mailbox

에서 메시지를 가져온다 좀 더 일반적이고 편한 전송 방식

Page 72: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제72

Mailboxes and PortsMailboxes and Ports

A mailbox can be private to one sender/receiver pair

The same mailbox can be shared among several senders and receivers

Port: a mailbox associated with one receiver and multiple senders used for client/server

applications: the receiver is the server

Page 73: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제73

Ownership of ports and mailboxesOwnership of ports and mailboxes

Port 는 수신 프로세스에 의해 생성되고 소유된다 port 는 수신 프로세스가 종료하면 해제된다

Mailbox 는 프로세스 요청에 의해 운영체제가 생성한다 요청한 프로세스가 소유하게 된다 소유권을 가진 프로세스의 요청이나 종료로 인해 해제된다

Page 74: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제74

메시지 형식메시지 형식 ((Message Format)Message Format)

헤드와 메시지 본체로 구성

control information: what to do if run out of

buffer space sequence numbers priority etc.

Page 75: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제75

메시지 전송을 통한 상호배제메시지 전송을 통한 상호배제

N 개의 프로세스가 공유할 mailbox mutex 을 생성한다

send() 는 non blocking receive() 는 mutex 가 비어

있으면 blocking empty 초기화 : send(mutex, “go”); receive() 를 처음 호출하는

프로세스 Pi 가 임계구역 (CS) 에 진입한다

다른 프로세스는 Pi 가 메시지를 전송할 때가 대기한다

Process Pi:var msg: message;repeat receive(mutex,msg); CS send(mutex,msg); RSforever

Page 76: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제76

메시지 전송을 통한메시지 전송을 통한 생산자 생산자 // 소비자 프로세스 문제소비자 프로세스 문제(1)(1)

const capacity = …; // buffering capacity null = …; // empty messagevar i : integer;procedure producer; var pmsg : message; begin while true do begin

receive(mayproduce, pmsg); pmsg ;= produce; send(mayconsume, pmsg);end

end;procedure consumer; var cmsg : message; begin while true do begin

receive(mayconsume, cmsg); consume(cmsg); send(mayproduce, null);end

end;

Page 77: Lecture #5

- 신라대학교 컴퓨터공학과 운영체제77

메시지 전송을 통한메시지 전송을 통한 생산자 생산자 // 소비자 프로세스 문제소비자 프로세스 문제(2)(2)

{ parent process }begin create_mailbox(mayproduce); create_mailbox(mayconsume); for i=1 to capacity do send(mayproduce, null); parbegin producer; consumer; parendend