59
Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of Distributed Systems Lab., SungKyunKwan University. 컴컴컴 컴컴컴컴 OS Operating System s

Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Embed Size (px)

Citation preview

Page 1: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 1

Chap. 7Process

Synchronization

Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved.No part of these slides may be reproduced, stored in a retrieval system or transmitted in any form orby any means, electronic, mechanical, photocopying, recording or otherwise, without the prior writtenpermission of Distributed Systems Lab., SungKyunKwan University.

컴퓨터 운영체제 OS Operating Systems

Page 2: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 2

Process synchronization Multiprogramming system 에는 여러 process 들이 존재 이들은 상호 독립적으로 움직임 Process 들이 동시에 독립적으로 진행됨으로 인하여 발생하는

문제점들이 있음 이러한 문제점들을 해결하는 기법

Process synchronization 기법 대부분 이러한 문제는 resource 에 대한 접근이나 shared

data 에 대한 접근 시에 발생

Introduction

Page 3: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 3

Asynchronous and Concurrent Processes

Asynchronous ( 비동기적 ) 각 프로세스들이 다른 프로세스들의 진행 상태 등을 전혀 모름

Concurrent ( 병행적 ) 시스템 내에 다수의 프로세스들이 동시에 존재함

병행 수행중인 프로세스들이 동시에 공유 데이터에 접근할 때 문제 발생 가능

병행성 (concurrency)- 여러 개의 process 들이 processor 를 번갈아 사용함

병렬성 (parallelism)- processor 가 여러 개 존재 , 여러 process 들이 동시 실행 가능

Note

Page 4: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 4

Terminologies

Shared data, critical data 여러 프로세스들에 의해 공동으로 사용되는 데이터

Critical section 공유 데이터에 접근하는 프로그램 세그먼트

Mutual exclusion 둘 이상 프로세스의 임계 지역 동시 진입을 금지시킴

기계어 명령 (machine instruction) 의 특성- 원자성 (atomicity), 분리불가능 (indivisible) ( 한 기계어 명령의 실행 도중에 인터럽트 받지 않음 )

Note

Terminologies

Page 5: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 5

0

sdata

memory

process-Pi process-Pj

공유 데이터 접근 예

sdata sdata + 1;sdata sdata + 1;

Page 6: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 6

기계어 수준에서의 공유 데이터 접근 예

Load Ri, sdata

0

sdata

process-Pi process-Pj

Add Ri, 1Store Ri, sdata

Load Ri, sdataAdd Ri, 1Store Ri, sdata

명령 수행 과정 (1) - ① ② ③ 또는 ① ② ③ - 결과 sdata = 2 명령 수행 과정 (2) - ① ② ③ - 결과 sdata = 1

Page 7: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 7

Mutual exclusion methods Mutual exclusion primitives

enterCS() primitiveo 임계 지역 진입 전 검사 과정o 다른 프로세스가 임계 지역 내에 존재하는지의 여부 검사

exitCS() primitiveo 임계 지역 벗어날 경우 처리 과정o 임계 지역에서 벗어남을 시스템에 알림

Critical Section CSk

enterCS(CSk)

exitCS(CSk) exitCS(CSk)

enterCS(CSk)

Pa.

.

Pb

Mutual exclusion primitives

.

.

.

.

.

.

Mutual Exclusion

Page 8: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 8

Requirements for mutual exclusion primitives Mutual exclusion

If a process Pi is executing in its CS, then no other processes can be executing in their CS’s

Progress Only those processes that are not executing in their remainder sect

ion can participate in the decision on which process will enter its CS next

Decision should not be postponed indefinitely Bounded waiting

Each process should be able to enter its CS after a finite number of trials

Requirements

Page 9: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 9

Critical Section

while (turn = 1) doendwhile;

turn 1;

P0repeat......

......until (false);

turn

while (turn = 0) doendwhile;

turn 0;

P1repeat......

......until (false);

does not satisfy the progress requirement

Two Process Mutual Exclusion

ME primitives version-1

Page 10: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 10

Critical Section

while (flag[1]) doendwhile;flag[0] true;

flag[0] false;

P0

repeat......

......until (false);

flag[0] flag[1] while (flag[0]) doendwhile;flag[1] true;

flag[1] false;

P1

repeat......

......until (false);

does not satisfy mutual exclusion requirements

Two Process Mutual Exclusion

ME primitives version-2

Page 11: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 11

Critical Section

flag[0] true;while (flag[1]) doendwhile;

flag[0] false;

P0

repeat......

......until (false);

flag[0] flag[1] flag[1] true;while (flag[0]) doendwhile;

flag[1] false;

P1

repeat......

......until (false);

Two Process Mutual Exclusion

ME primitives version-3

does not satisfy the progress requirement

Page 12: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 12

Dekker’s algorithm

Critical Section

flag[0] true;while (flag[1]) do if (turn = 1) then begin flag[0] false; while (trun = 1) do endwhile; flag[0] true; end;endwhile;

P0repeat......

flag[0] flag[1]

turn 1;flag[0] false;......until (false);

flag[1] true;while (flag[0]) do if (turn = 0) then begin flag[1] false; while (trun = 0) do endwhile; flag[1] true; end;endwhile;

P1repeat......

turn 0;flag[1] false;......until (false);

turn

Dekker’s algorithm

Two Process Mutual Exclusion

Page 13: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 13

Critical Section

flag[0] true;turn 1;while (flag[1] and trun = 1) doendwhile;

P0repeat...... flag[0] flag[1]

flag[0] false;......until (false);

P1repeat......

flag[1] false;......until (false);

turn

flag[1] true;turn 0;while (flag[0] and trun = 0) doendwhile;

Peterson’s algorithm

Two Process Mutual Exclusion Peterson’s algorithm

Page 14: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 14

N-process mutual exclusion schemes Dijkstra’s algorithm

무기한 연기의 가능성이 있음 Knuth’s algorithm

무기한 연기의 가능성을 제거 지연 시간이 매우 큼

Eisenberg and McGuire’s algorithm 유한 시간 (n-1 번 ) 내의 시도 후 임계 지역 진입 보장

Lamport’s algorithm 분산 시스템 환경을 위한 상호 배제 기법

Bakery algorithm

N-Process Mutual Exclusion

Page 15: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 15

flag[] 값idle

want-in

in-CS 프로세스의 임계 지역 진입 시도 2 단계 및 임계 지역 내에 있을 때프로세스의 임계 지역 진입 시도 1 단계일 때프로세스가 임계 지역 진입을 시도하고 있지 않을 때

의 미

Dijkstra’s algorithm 의 flag[] 변수

N-Process Mutual Exclusion Dijkstra’s algorithm

Page 16: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 16

Critical Section

repeat /* 임계 지역 진입시도 1 단계 */ flag[i] want-in; while (turn i) do if (flag[turn] = idle) then trun i; endwhile; /* 임계 지역 진입시도 1 단계 */ flag[i] in-CS; j 0; while ((j < n) and (j = i or flag[j] in-CS)) do j j + 1; endwhile;until (j n);

프로세스 Pirepeat......

flag[1]

flag[i] idle;......until (false);

turn

flag[n]

......

...

Dijkstra’s algorithm

Page 17: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 17

Hardware support for mutual exclusion ME 를 위한 software solution 들의 문제점

Low speed Primitive 실행 중 preemption 가능성

ME 를 위한 hardware support 예 IBM 의 TS(Test and Set) 명령 (machine instruction) Atomic, indivisible

Machine instruction 의 특성- Atomic, indivisible ( 한 기계어 명령의 실행 도중에 인터럽트 받지 않음 )

Note

Synchronization Hardware

Page 18: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 18

Definition of TS() instruction Atomic(indivisible) operation

Boolean TS(boolean &target) {

boolean rv = target;

target = true;

return rv;

}

Synchronization Hardware

Page 19: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 19

Critical Section

while (TS(lock)) doendwhile;

Pirepeat......

lock false;......until (false);

...

...

...

...

TS 명령을 사용한 ME algorithm

Initiallylock = false;

Synchronization Hardware Mutual exclusion with TS() instruction

Page 20: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 20

상기의 각종 mutual exclusion 기법들의 단점 busy waiting inefficiency

busy waiting 방지하는 mutual exclusion 기법들 Semaphore 기법 sequencer/eventcount 기법

Critical section 에 즉시 진입할 수 없는 process 들을 대기(asleep/blocked/wait) 상태로 전이시킴

Summary

Page 21: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 21

Semaphore Spinlock

정의 : 세머퍼

integer variable P() 연산과 V() 연산 , 그리고 초기화 연산에 의해서만 접근 가능

P(S) { while (S 0) do endwhile; S S – 1;}

V(S) { S S + 1;}

P() and V() are indivisible operations

Page 22: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 22

Semaphore Spinlock for mutual exclusion

Critical Section

P(active);

V(active);

Pi

repeat......

......until (false);

P(active);

V(active);

Pj

repeat......

......until (false);

1

active

active = 1 : 임계 지역을 실행중인 프로세스 없음 active = 0 : 임계 지역을 실행중인 프로세스 있음

Spinlock 을 이용한 ME

Page 23: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 23

Semaphore Spinlock

Used in multiprocessor systems, not in uniprocessor systems

Solaris 2, Windows 2000

Page 24: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 24

Semaphore 1965 년 Dijkstra 제안 Busy waiting 문제 해결

정의 : Semaphore 일종의 정수형 변수 P() 연산과 V() 연산 , 그리고 초기화 연산에 의해서만 접근 가능 임의의 세머퍼 S 에는 하나의 대기 큐 Qs 가 할당됨

Binary semaphore Semaphore 변수가 0 과 1 의 두 종류의 값만을 갖는 경우 ME 또는 process synchronization 의 목적으로 사용

Counting semaphore Semaphore 변수가 0 이상의 모든 정수값을 가지는 경우 Producer-consumer 문제 등의 해결을 위해 사용

Page 25: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 25

Semaphore 변수에 접근 가능한 연산 initialization 연산

semaphore 변수에 초기값을 부여하는 연산 P() 연산 , V() 연산 : 두 연산 모두 indivisible operation

정의 : P(S) 연산

if (S > 0) then S S - 1; else wait on the queue Qs ;

정의 : V(S) 연산

if ( waiting processes on Qs)

then wakeup one of them; else S S + 1;

Semaphore

Page 26: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 26

Semaphore Semaphore 이용하여 해결 가능한 concurrent

programming problems Mutual exclusion problem Process synchronization problem Producer-consumer problem Reader-writer problem Dining philosopher problem Etc

Page 27: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 27

Mutual exclusion

Critical Section

P(active);

V(active);

Pi

repeat......

......until (false);

P(active);

V(active);

Pj

repeat......

......until (false);

1

active

active = 1 : 임계 지역을 실행중인 프로세스 없음 active = 0 : 임계 지역을 실행중인 프로세스 있음

Semaphore 를 이용한 ME

Semaphore

Page 28: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 28

Process synchronization

Semaphore

process-Pi

Li :

process-Pj

Lj :

프로세스 Pi 는프로세스 Pj 가

Lj 지점을 통과할 때까지Li 지점에서 대기함

Page 29: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 29

Process synchronization

Semaphore

process-Pi

Li : P(sync);

process-Pj

Lj : V(sync)

프로세스 Pi 는프로세스 Pj 가

Lj 지점을 통과할 때까지Li 지점에서 대기함

0

sync

Page 30: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 30

Producer-consumer problem Producer processes

메시지를 생성하는 process group Consumer processes

메시지를 전달 받는 process group

Producer process Shared memory buf Consumer process

메시지 생성 , 적재 메시지 인출 , 소비

Single buffer 의 경우 Semaphore 변수 consumed/produced 사용 Producer/consumer process 가 번갈아가며 buffer 에 메시지를

적재하고 소비하는 일을 반복함

Semaphore

Page 31: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 31

(shared variables)var consumed : semaphore 1, produced : semaphore 0, buffer : message;

repeat ... create a new message M; P(consumed); buffer M; V(produced); ...until(false);

repeat ... P(produced); m buffer; V(consumed); consume the message m; ...until(false);

Producer PiConsumer Cj

Single buffer 의 경우 producer-consumer 문제

Semaphore

Page 32: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 32

buffer[0]buffer[1]

buffer[2]

buffer[N-1]

buffer[3]buffer[4]

buffer[5]

생산자프로세스

소비자프로세스

Multiple, circular buffer 의 경우 producer-consumer 문제

Semaphore Producer-consumer problem

Multiple buffer 의 경우

Page 33: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 33

(shared variables)var nrfull : semaphore 0, nrempty : semaphore N, mutexP : semaphore 1, mutexC : semaphore 1, buffer : array[0..N-1] of message, in, out : 0..N-1 0,0;

repeat ... create a new message M; P(mutexP); P(nrempty); buffer[in] M; in (in + 1) mod N; V(nrfull); V(mutexP); ...until(false);

Producer Ⓘ Consumer Ⓙ

Multiple, circular buffer 의 경우 producer-consumer code

repeat ... P(mutexC); P(nrfull); m buffer[out]; out (out + 1) mod N; V(nrempty); V(mutexC); ...until(false);

Semaphore

Page 34: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 34

Reader-writer 문제 Reader process

임의의 data 에 대해 읽기 연산만 수행 Writer process

임의의 data 에 대해 갱신 연산을 수행 Data integrity

Reader process 들간 data 에 동시 접근 가능 Writer process 들간 또는 reader-writer 간 data 에 동시 접근

불가능 해결법의 종류

Reader/writer process 들에 대한 priority 부여 방법에 따라o weak reader preference solutiono strong reader preference solutiono writer preference solution

Semaphore

Page 35: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 35

(shared variables)var wmutex, rmutex : semaphore := 1, 1, nreaders : integer := 0

repeat ... P(rmutex); if (nreaders = 0) then P(wmutex); endif; nreaders nreaders + 1; V(rmutex); Perform read operations; P(rmutex); nreaders nreaders - 1; if (nreaders = 0) then V(wmutex); endif; V(rmutex); ...until(false);

Reader RiWriter Wj

repeat ... P(wmutex); Perform write operations V(wmutex); ...until(false);

Weak reader preference solution

Reader-Writer code

Semaphore

Page 36: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 36

Semaphore 이용 기법의 특성 Busy waiting 문제 해결 진행 불가능한 경우 즉시 block 됨 Semaphore queue 에서 대기중인 프로세스들의 wakeup

순서는 결정되지 않음 Starvation 문제점

Semaphore

Page 37: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 37

Eventcount/Sequencer

Eventcount 와 sequencer 를 이용한 기법 은행의 서비스 순서가 기재된 티켓과 같은 형태로 process

들간의 synchronization 및 mutual exclusion 을 이루는 기법

정의 : Sequencer 일종의 정수형 변수 생성 즉시 0 으로 초기화되며 그 값이 감소하지 않음 발생 사건들의 순서 유지 ticket() 연산으로만 이 변수에 접근 가능

정의 : ticket(S) S 는 sequencer 변수임 현재까지 ticket() 연산이 호출되었던 횟수를 반환하는 함수 indivisible operation

Page 38: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 38

정의 : read(E) E 는 eventcount 변수임 현재 eventcount E 가 가지고 있는 값을 반환함

정의 : advance(E) E 는 eventcount 변수임 E E + 1; wakeup the process waiting for E’s value to reach to the current value just attained;

정의 : await(E, v) E 는 eventcount 변수 , v 는 정수형 변수임 if ( E < v ) then place the executing process in the waiting queue associated with E and invoke CPU scheduler; endif

정의 : Eventcount 일종의 정수형 변수 생성 즉시 0 으로 초기화되며 그 값이 감소하지 않음 특정 사건들의 발생 횟수를 기록 , 추적하기 위하여 사용 read(), advance(), await() 연산으로만 이 변수에 접근 가능

Eventcount/Sequencer

Page 39: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 39

Mutual exclusion

Critical Section

v ticket(S); await(E, v);

Pirepeat......

advance(E);......until (false);

...

...

...

...

Eventcount/sequencer 를 이용한 ME 기법

Eventcount/Sequencer

Page 40: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 40

Producer-consumer problem

(shared variables)var Pticket, Cticket : sequencer, In, Out : eventcount, buffer : array[0..N-1] of message;

var t : integer;

repeat ... Create a new message M; t ticket(Pticket); await(In, t); await(Out, t - N + 1); buffer[t mod N] M; advance(In); ...until(false)

Producer PiConsumer Cj

Producer-consumer code

var u : integer;

repeat ... u ticket(Cticket); await(Out, u); await(In, u + 1); m buffer[u mod N] ; advance(Out); Consume the message m; ...until(false)

Eventcount/Sequencer

Page 41: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 41

Eventcount 와 sequencer 를 이용한 기법의 특성

Busy waiting 방지 가능 Block 된 순서대로 wakeup 됨 (FIFO 스케줄링 )

Starvation 문제점 해결

Eventcount/Sequencer

Page 42: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 42

Conclusion multiprogramming system 내의 process 특성

Asynchronous Concurrent 공유 데이타의 관리 및 프로세스들간의 정보 전달 지원을 위해

상호 배제 기법이나 프로세스 동기화 기법이 필요함 상호 배제 및 동기화를 위한 소프트웨어적 해결법

Dekker 알고리즘 Peterson 알고리즘

상호 배제 및 동기화를 위한 하드웨어적 해결법 IMB 에서 제안된 TS 명령 사용 소프트웨어적 해결법의 속도 문제 해결

Semaphore 와 Eventcount/Sequencer busy waiting 문제 해결

Page 43: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 43

Concurrent Programming

Constructs

Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved.No part of these slides may be reproduced, stored in a retrieval system or transmitted in any form orby any means, electronic, mechanical, photocopying, recording or otherwise, without the prior writtenpermission of Distributed Systems Lab., SungKyunKwan University.

컴퓨터 운영체제 OS Operating Systems

Page 44: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 44

Introduction Mutual exclusion & process synchronization 기법

Low level mechanisms Dekker algorithm, Peterson algorithm Dijkstra, Knuth, Eisenberg, MacGuire/Lamport algorithms Hardware support (TS instruction) Semaphore Eventcount/sequencer 프로그래머의 사용이 매우 불편 , 오류 범하기 쉬움

High-level mechanisms Monitor Path expressions Serializers Critical regions, conditional critical regions 대부분 객체지향 개념 (object-oriented concept) 사용자들이 사용하기 쉬움

Page 45: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 45

Monitor Definition of monitor

Shared data 와 critical section code 들의 집합

Monitor 의 구조

Monitor entry queues

Condition queues

Waiting signaler queue

Critical data &

Critical sections

Page 46: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 46

Monitor 의 구조 및 기능 Entry queues

Monitor 내의 procedure 수만큼 존재 Mutual exclusion 자동 보장

Monitor 내에는 항상 하나 이하의 process 만 진입 가능 Information hiding

Shared data 에 대한 접근o Monitor 내에 진입하여 자신이 호출한 procedure 를

실행하는 방법 외에 다른 방법으로 접근 불가능 Condition queues

Monitor 내에 진입 후 필요할 경우 process 가 원하는 조건에 해당하는 condition queue 에서 대기

Signaler queue Monitor 에 항상 하나의 signaler queue 가 존재 signal() 명령을 실행한 process 가 임시 대기

Monitor

Page 47: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 47

Resource allocation

resourceRiAllocator

entry queue for requestRi()

signaler queue

entry queue for releaseRi() condition queue RiI

sFreeRiIsAvailable

requestRi() releaseRi()

Monitor Example

Page 48: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 48

resourceRiAllocator code

monitor resourceRiAllocator;var RiIsAvailable : boolean, RiIsFree : condition;procedure requestRi();begin if (¬RiIsAvailable) then RiIsFree.wait(); RiIsAvailable false;end;procedure releaseRi():begin RiIsAvailable true; RiIsFree.signal();end;

begin RiIsAvailable true;end.

Monitor Example

Page 49: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 49

Resource allocation scenario

Monitor state 1

entry queue for requestRi()

signaler queue

entry queue for releaseRi() condition queue RiI

sFree

0RiIsAvailable

requestRi() releaseRi()

Pk Pm

• 자원 Ri 가 프로세스 Pj 에게 할당되고 , • 프로세스 Pk 가 Ri 를 요구한 후 , 다시 Pm 이 자원 Ri 를 요구한 경우

Pj Ri

Monitor Example

Page 50: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 50

entry queue for requestRi()

signaler queue

entry queue for releaseRi() condition queue RiI

sFree

1RilsAvailable

Pk

requestRi() releaseRi()

Pm

Pj

• 프로세스 Pj 가 자원 Ri 를 반납하고자 하고 • 프로세스 Pk 가 wakeup 된다고 가정하는 경우

Monitor Example Resource allocation scenario

Monitor state 2

Page 51: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 51

entry queue for requestRi()

signaler queue

entry queue for releaseRi() condition queue Ril

sFree

0RilsAvailable

Pj

requestRi() releaseRi()

Pm

• 프로세스 Pk 가 자원 Ri 를 할당받아 모니터를 벗어난 후 • 프로세스 Pj 가 모니터에 다시 진입하여 나머지 실행을 마치게 되는 경우

Pk Ri

Monitor state 3

Monitor Example Resource allocation scenario

Page 52: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 52

Producer-consumer relationship Multiple circular buffer

buffer[1]

buffer[2]

buffer[N-1]

buffer[3]buffer[4]

buffer[5]

buffer[0]

fillBuf() emptyBuf()

entry queuefor fillBuf()

entry queuefor emptyBuf()

bufHasData

bufHasSpace

signaler queue

0validBufsoutin

Producer-consumer monitor

0 0

Monitor Example

Page 53: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 53

Producer-consumer monitor code

monitor ringbuffer;var buffer : array[0..N-1] of message, validBufs : 0..N, in : 0..N-1, out : 0..N-1, vufHasData, bufHasSpace : condition;procedure fillBuf(data : message);begin if (validBufs = N) then bufHasSpace.wait(); buffer[in] data; validBufs validBufs + 1; in (in + 1) mod N; bufHasData.signal();end;procedure emptyBuf(var data : message):begin if (validBufs = 0) then bufHasData.wait(); data buffer[out]; validBufs validBufs - 1; out (out + 1) mod N; bufHasSpace.signal();end;

begin validBufs 0; in 0; out 0; end.

Page 54: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 54

Reader-writer 문제 Reader/writer process 들간의 데이터 무결성 보장 기법 Writer process 에 의한 데이터 접근 시에만 상호 배제 및

동기화 필요

Monitor 구성 Two variables

o 현재 읽기 작업을 진행하고 있는 reader process 의 수o 현재 writer process 가 쓰기 작업 중인지 표시

2 condition queueso reader/writer process 가 대기해야 할 경우에 사용

4 procedureso Reader(writer) process 가 읽기 ( 쓰기 ) 작업을 원할

경우에 호출 , 읽기 ( 쓰기 ) 작업을 마쳤을 때 호출

Monitor Example

Page 55: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 55

Reader-writer monitor code

monitor readers_and_writers;var numReaders : integer, writing : boolean, readingAllowed, writingAllowed : conditon;procedure beginReading;begin if (writing or queue(writingAllowed)) then readingAllowed.wait(); numReaders numReaders + 1; if (queue(readingAllowed)) then readingAllowed.signal();end;procedure finishReading:begin numReaders numReaders - 1; if (numReaders = 0) then writingAllowed.signal();end;procedure beginWriting;begin if (numReaders > 0 or writing) then writingAllowed.wait() writing true;end;procedure finishWriting:begin writing false; if (queue(readingAllowed)) then readingAllowed.signal(); else writingAllowed.signal();end;begin numReaders 0; writing false; end.

Page 56: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 56

Dining philosopher

P5P2

P3 P4

spaghetti

P1

Dining-philosopher 문제

Monitor Example

Page 57: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 57

Dining-philosopher monitor code

monitor dining_philosophers;var numForks : array[0..4] of integer, ready : array[0..4] of condition, i : integer;procedure pickup(me);var me : integer;begin if (numForks[me] 2) then ready[me].wait(); numForks[right(me)] numForks[right(me)] - 1; numForks[left(me)] numForks[left(me)] - 1;end;procedure putdown(me):var me : integer;begin numForks[right(me)] numForks[right(me)] + 1; numForks[left(me)] numForks[left(me)] + 1; if (numForks[right(me)] = 2) then ready(right(me)].signal(); if (numForks[left(me)] = 2) then ready(left(me)].signal(); end;

begin

for i 0 to 4 do numForks[i] 2; end.

Page 58: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 58

Code for philosopher process

do forever

pickup(i);

eating;

putdown(i);

thinking;end.

Pi

Page 59: Page 1 Chap. 7 Process Synchronization Copyright(c) 1999, Distributed Systems Lab., SungKyunKwan University, All rights reserved. No part of these slides

Page 59

Conclusion

Low-level concurrent programming constructs Programmer 의 사용이 불편하고 오류 범하기 쉬움

High-level concurrent programming constructs Monitor, path expressions, serializers, critical regions 등

사용자들이 병행 프로그래밍을 보다 쉽게 할 수 있도록 지원함 객체지향 개념코딩 중 오류 발생 가능성을 크게 줄임