1 / 69

Process Synchronization: Critical-Section Problem and Solutions

Learn about the critical-section problem and solutions for process synchronization, including mutual exclusion, progress, and bounded waiting. Explore software and hardware solutions for synchronization.

bondc
Download Presentation

Process Synchronization: Critical-Section Problem and Solutions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6: Process Synchronization

  2. Chapter 6: Process Synchronization • Background • The Critical-Section Problem • Peterson’s Solution • Synchronization Hardware • Mutex Locks • Semaphores • Classic Problems of Synchronization • Monitors • Synchronization Examples • Alternative Approaches

  3. Objectives • To present the concept of process synchronization. • 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 examine several classical process-synchronization problems • To explore several tools that are used to solve process synchronization problems

  4. Background • Processes can execute concurrently • May be interrupted at any time, partially completing execution • Concurrent access to shared data may result in data inconsistency • Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes

  5. Producer while (true) { /* produce an item in next produced */ while (counter == BUFFER_SIZE) ; /* do nothing */ buffer[in] = next_produced; in = (in + 1) % BUFFER_SIZE; counter++; } next 항목 생성 후, buffer에 write Illustration of the problem:Suppose that we wanted to provide a solution to the consumer-producer problem that fills allthe buffers. We can do so by having an integer counterthat keeps track of the number of full buffers. Initially, counteris 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. Consumer while (true) { while (counter == 0) ; /* do nothing */ next_consumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; counter--; /* consume the item in next consumed */ } buffer에서 read함

  6. Race Condition • counter++ could be implemented asregister1 = counter register1 = register1 + 1 counter = register1 • counter–could be implemented asregister2 = counter register2 = register2 – 1 counter = register2 • Consider this execution interleaving with “count = 5” initially: S0: producer execute register1 = counter{register1 = 5}S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = counter{register2 = 5} S3: consumer execute register2 = register2 – 1 {register2 = 4} S4: producer execute counter = register1 {counter = 6 } S5: consumer execute counter = register2 {counter = 4} • 두 process가 동시에 counter 변수에 접근함 ! • A situation like this, where several processes access and manipulate the same data concurrently and the outcome of the execution depends on the particular order in which the access takes place, is called a race condition. • 최종 실행 결과는 프로세스나 thread 의 실행 순서에 의해 달라져 버림. 프로세스 동기화 필요함

  7. Critical Section Problem • Consider system of nprocesses {p0, p1, … pn-1} • Each process has critical section segment of code • Process may be changing shared variables, updating table, writing file, etc. • When one process in critical section, no other may be in its critical section • Critical section problem is to design protocol to solve this • Each process must ask permission to enter critical section in entry section, may follow critical section with exit section, then remainder section

  8. Critical Section • A Critical Section is a code segment that accesses shared variables and has to be executed as an atomic action. • It means that in a group of cooperating processes, at a given point of time, only one process must be executing its critical section. • If any other process also wants to execute its critical section, it must wait until the first one finishes • General structure of process Pi • 진입 구역(entry section) • 임계 구역에 진입하기 위해 허용을 요구하는 코드 영역 • 출구 구역(exit section) • 임계 구역 다음에 나오는 영역으로써, 임계 구역을 벗어나기 위한 코드 영역 • 잔류 구역(remainder section) • 프로그램의 나머지 코드 부분 • A solution to the critical section problem must satisfy the following three conditions: • Mutual Exclusion • Progress • Bounded Waiting

  9. Algorithm for Process Pi

  10. Solution to Critical-Section Problem • Mutual Exclusion (상호배제) – If process Piis executing in its critical section, then no other processes can be executing in their critical sections • Progress (진행)- If no process is executing in its critical section and there exist some processes that wish to enter their critical section, then the selection of the processes that will enter the critical section next cannot be postponed indefinitely • Deadlock avoidance 필요 • Bounded Waiting (한계대기) - A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted • 하나의 프로세스가 임계 구역 진입을 요청한 후, 진입이 허용될 때까지 다른 프로세스가 임계 구역을 진입하는 횟수(시간)에 제한을 둬야 함 • 만족시키지 못할 경우 starvation(기아상태) 유발 • Assume that each process executes at a nonzero speed • No assumption concerning relative speed of the n processes

  11. Critical-Section Handling in OS • Critical section 관련 해결책 분류 • Software solutions • software algorithms who’s correctness does not rely on any other assumptions • Hardware solutions • rely on some special machine instructions • OS solutions • OS provide some functions and data structures to the programmer Two approaches depending on if kernel is preemptive or non-preemptive • Preemptive– allows preemption of process when running in kernel mode • Non-preemptive – runs until exits kernel mode, blocks, or voluntarily yields CPU • Essentially free of race conditions in kernel mode

  12. SW 해결책 • process가 두 개가 있는 경우의 해결책 • 두개의 processes : P0, P1 • Algorithm 1, 2  incorrect • Algorithm 3 --> Correct (Peterson's algorithm) • n개의 process를 위한 해결책 • bakery algorithm

  13. SW 해결책 - Algorithm 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 // “진행” 요구사항 만족 못시킴 • 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. Process Pi: repeat while(turn!=i){}; CS turn:=j; RS until FALSE small RS large RS 그림 소스: Distributed systems Lab@SKKU

  14. SW 해결책 - Algorithm 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; RS until FALSE 그림 소스: Distributed systems Lab@SKKU

  15. SW 해결책 - Algorithm 3, Peterson’s Solution • Good algorithmic description of solving the problem • Two process solution • Assume that the loadand store machine-language instructions are atomic; that is, cannot be interrupted • The two processes share two variables: • int turn; • Boolean flag[2] • The variable turn indicates whose turn it is to enter the critical section • The flagarray is used to indicate if a process is ready to enter the critical section. flag[i] = trueimplies that process Pi is ready!

  16. Algorithm for Process Pi • Initialization: flag[0]:=flag[1]:=false, turn := 0 or 1 ; • flag은 해당 Process가 CS 들어갈 준비되어 있음 표현, turn=0는 P0, turn=1은 P1이 CS에서 실행될 수 있음을 의미. • 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. 결국 turn 값은 0 혹은 1 둘 중 하나임 • CS에 들어가기 위해 P0는 flag[0]=1로하고turn=1로 지정  이는 process 1이 CS에 들어가고 싶으면 들어가라는 말. • P1이 while()에서 기다리다, turn=1로되면, P1은 CS로 들어감 • 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; RS until FALSE 그림 소스: Distributed systems Lab@SKKU

  17. Peterson’s Solution (Cont.) • Mutual exclusion is preserved since: • P0 and P1are both in CS only if flag[0] = flag[1] = true and only if turn = i for each Pi(이때 turn 변수는 하나의 값만 가짐. 이에, CS영역은 하나만 수행됨) • The progress and bounded waiting requirements are satisfied: • Pi의 CS영역 진입 제한은 while (flag[j]==true && turn==j) 때문①. Pj가 CS영역에 진입할 준비가 안되었을때는 flag[j] false라는 것을 의미함. 즉 이 경우 Pi는 CS에 진입할 수 있음① • Pj가 자신의 flag[j] true로 하고 CS 진입하고자 while문을 수행함②③. 이때 turn ==i 이라면Pi 의 CS 영역으로 진입하고①,turn==j이면, Pj 의 CS 영역에 진입③ • 한편 Pj는 CS 영역 실행 후, flag[j] false로 재지정하여④,상대방Pi가 CS에 진입하도록 함① ② ① ③ ④

  18. Peterson’s Solution (Cont.) • The progress and bounded waiting requirements are satisfied: (계속) • Pj가 flag[j] true로 재지정하면반드시 turn 값도i로 지정해야②⑤. • Pi는 while 문을 수행하는 동안①,turn 값을 바꾸지 않으므로(즉 turn 값이 i로 지정된것 ⑤ 유지), Pi는 Pj가 지난번에 진입했다면 Pi도 한번은 CS 진입 보장됨(progress 보장)①. ② ⑤ ①

  19. Synchronization Hardware • Many systems provide hardware support for implementing the critical section code. • All solutions below based on idea of locking • Protecting critical regions via locks • Uniprocessors – could disable interrupts • Currently running code would execute without preemption • Generally too inefficient on multiprocessor systems • On a multiprocessor: mutual exclusion is not preserved • Generally not an acceptable solution • Operating systems using this not broadly scalable • Modern machines provide special atomic hardware instructions • Atomic = non-interruptible • Either test memory word and set value • Or swap contents of two memory words

  20. Solution to Critical-section Problem Using Locks do { acquire lock critical section release lock remainder section } while (TRUE);

  21. test_and_set Instruction • 가정) 초기 lock false; 즉 CS 진입가능. lock이 true이면 계속 test_and_set에서 기다림 • target이 P0라면 해당 P0의 상태(lock free)를 return하면서, P0는 lock을 TRUE로 set함 • P0의 CS로 진입 (lock free였으므로. 한번 테스트해서 free였으면 한번만 CS 진입보장을 위해 TRUE로 lock 변경) • P0의 CS 실행 완료하면,CS 영역진입 허용 위해 lock을 false로 변경 booleantest_and_set (boolean *target) { booleanrv = *target; *target = TRUE; return rv: } • Executed atomically • Returns the original value of passed parameter • Set the new value of passed parameter to “TRUE”. • Shared Boolean variable lock, initialized to FALSE • do { while (test_and_set(&lock)) ; /* do nothing */ /* critical section */ lock = false; /* remainder section */ } while (true);

  22. compare_and_swap Instruction intcompare_and_swap(int *value, int expected, intnew_value) { int temp = *value; if (*value == expected) *value = new_value; return temp; } • Executed atomically • Returns the original value of passed parameter “value” • Set the variable “value” the value of the passed parameter “new_value” but only if “value” ==“expected”. That is, the swap takes place only under this condition. • Shared integer “lock” initialized to 0; • Solution: do { while (compare_and_swap(&lock, 0, 1) != 0) ; /* do nothing */ /* critical section */ lock = 0; /* remainder section */ } while (true); • lock의 value값이 true이면, 계속 기다림. • lock값과 expected 값이 같으면, new_value로 바꿈(lock을 new_value로 바꿈) 이들은 한정된 대기조건 만족못시킴!

  23. Bounded-waiting Mutual Exclusion with test_and_set • booleanwaiting[n]; • bloolean lock; • // 모두 false로 초기화됨 do { waiting[i] = true; key = true; while (waiting[i] && key) key = test_and_set(&lock); waiting[i] = false; /* critical section */ j = (i + 1) % n; while ((j != i) && !waiting[j]) j = (j + 1) % n; if (j == i) lock = false; else waiting[j] = false; /* remainder section */ } while (true); • Pi가 waiting하고 있으며, key가 true인 경우, CS진입위해 test_and_set check함 • lock이 false이면 key가 false가 되어 CS에 진입됨 • CS 영역 진입하면 Pi는 waiting하지 않는다함 CS에서 나오면서 다른 Pj상태를 i+1,…,i-1까지 순환하면서, check함. waiting하는 j가 있으면, 해당 j를 waiting[j] false로 하여, 해당Pj가 CS에 진입가능하게 함. 자신일 경우에는 lock을 해제함(CS 실행했기때문에, 다른 Pj가 CS 진입가능하도록) 한정된 대기조건 만족시킴

  24. Mutex Locks • Previous solutions are complicated and generally inaccessible to application programmers • OS designers build software tools to solve critical section problem • Simplest is mutex lock • Protect a critical section by first acquire()a lock then release()the lock • Boolean variable indicating if lock is available or not • Calls to acquire()and release()must be atomic • Usually implemented via hardware atomic instructions • But this solution requires busy waiting • This lock therefore called a spinlock

  25. acquire() and release() • acquire() { while (!available) ; /* busy wait */ available = false;; } • release() { available = true; } • do { acquire lock critical section release lock remainder section } while (true); • lock을 사용할 수 있으면, acquire()되고 lock은 사용 불가능 상태로 바꿈

  26. Semaphore • sema : 그리스어로 sign을 의미 • Synchronization tool that provides more sophisticated ways (than Mutex locks) for process to synchronize their activities. • Semaphore S – integer variable • Can only be accessed via two indivisible (atomic) operations • wait()and signal() • Originally called P()and V() • Definition of the wait() operation wait(S) { while (S <= 0) ; // busy wait S--; } • Definition of the signal() operation signal(S) { S++; }

  27. Semaphore Usage • Counting semaphore – integer value can range over an unrestricted domain • Binary semaphore – integer value can range only between 0 and 1 • Same as a mutex lock • Can solve various synchronization problems • Consider P1 and P2 that require S1to happen before S2 Create a semaphore “synch” initialized to 0 P1: S1; signal(synch); P2: wait(synch); S2; • Can implement a counting semaphore S as a binary semaphore

  28. Semaphore Implementation • Must guarantee that no two processes can execute the wait() and signal() on the same semaphore at the same time • Thus, the implementation becomes the critical section problem where the wait and signal code are placed in the critical section • Could now have busy waitingin critical section implementation • But implementation code is short • Little busy waiting if critical section rarely occupied • Note that applications may spend lots of time in critical sections and therefore this is not a good solution

  29. Semaphore Implementation with no Busy waiting • With each semaphore there is an associated waiting queue • Each entry in a waiting queue has two data items: • value (of type integer) • pointer to next record in the list • Two operations: • block– place the process invoking the operation on the appropriate waiting queue • wakeup– remove one of processes in the waiting queue and place it in the ready queue • typedefstruct{ int value; struct process *list; } semaphore;

  30. Implementation with no Busy waiting (Cont.) 결국 음수값의 절대값은 semaphore 대기프로세스 수 wait(semaphore *S) { S->value--; if (S->value < 0) { add this process to S->list; block(); // 자신을 호출한 프로세스 중지시키는 셈 } } signal(semaphore *S) { S->value++; if (S->value <= 0) { remove a process P from S->list; wakeup(P); // 봉쇄된 프로세스 P의 실행 재개 } }

  31. Deadlock and Starvation • Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes • Let S andQbe two semaphores initialized to 1 P0P1 wait(S); wait(Q); wait(Q); wait(S); ... ... signal(S); signal(Q); signal(Q); signal(S); • Starvation– indefinite blocking • A process may never be removed from the semaphore queue in which it is suspended • Priority Inversion(우선순위 역전문제)– Scheduling problem when lower-priority process holds a lock needed by higher-priority process • Solved via priority-inheritance protocol (우선순위 상속 프로토콜) P0가 wait(S)실행하고 P1이 wait(Q)를 실행했음 --> P0는 wait(Q) 상황.즉 P1이 signal(Q)를 실행해야 진행가능함.. 진행 못함  deadlock!

  32. Classical Problems of Synchronization • Classical problems used to test newly-proposed synchronization schemes • Bounded-Buffer Problem • Readers and Writers Problem • Dining-Philosophers Problem

  33. Bounded-Buffer Problem • n buffers, each can hold one item • Semaphore mutex initialized to the value 1 • Semaphore full initialized to the value 0 • Semaphore emptyinitialized to the value n

  34. 1 0 N Bounded-Buffer Problem Semaphores Mutex Full Empty while (true) { // produce an item wait (empty); wait (mutex); // add the item to the buffer signal (mutex); signal (full); } while (true) { wait (full); wait (mutex); // remove an item from buffer signal (mutex); signal (empty); // consume the removed item } Consumer Producer • producer 동작: 써야할 item 있음 가용 buffer 있을때까지 기다림. 쓸 때는 상호배제 필요  … • mutex: buffer pool 접근위한 상호 배제 기능 제공 • empty: 비어있는 buffer 수 • full: 채워진 buffer 수

  35. Bounded Buffer Problem (Cont.) • The structure of the producer process do { ... /* produce an item in next_produced */ ... wait(empty); wait(mutex); ... /* add next produced to the buffer */ ... signal(mutex); signal(full); } while (true);

  36. Bounded Buffer Problem (Cont.) • The structure of the consumer process Do { wait(full); wait(mutex); ... /* remove an item from buffer to next_consumed */ ... signal(mutex); signal(empty); ... /* consume the item in next consumed */ ... } while (true);

  37. Readers-Writers Problem • A data set is shared among a number of concurrent processes • Readers – only read the data set; they do notperform any updates • Writers – can both read and write • Problem : if a writer and some other process (either a reader or a writer) access the database simultaneously, chaos may occurs • Solution: writers should have exclusive access to the shared database while writing to the database.(Writer가 쓰기작업할 동안에는 공유 데이터에 대한 배타적 접근권한 가지게 할 필요 있음) • Several variations of how readers and writers are considered • (1) first readers-writers problem: requires that no reader be kept waiting unless a writer has already obtained permission to use the shared object. In other words, no reader should wait for other readers to finish simply because a writer is waiting • (2) Second readers-writes problem: once a writer is ready, that writer perform its write as soon as possible. In other words, if a writer is waiting to access the object, no new readers may start reading. • 둘다 starvation을 유발함. (1)은 Writer를 starvation할 수 있고 (2)는 reader를 starvation할 수 있음

  38. Readers-Writers Problem (Cont.) • 1st Readers-Writers Problem에 대한 해결책 제시 • Semaphorerw_mutexinitialized to 1 • Semaphore mutexinitialized to 1 • Integer read_count initialized to 0 • mutex: read_count갱신시 상호 배제 보장용semaphore • rw_mutex: reader와 writer가 모두 공유하는 semaphore • read_count:현재 몇 개의 프로세서들이 이 객체를 읽는지 알려줌

  39. mutex: read_count갱신시 상호 배제 보장용 • rw_mutex: reader와 writer가 모두 공유 • read_count: 현재 몇 개의 프로세서들이 객체 읽는지 알려줌 • The structure of a writer process do {wait(rw_mutex); .../* writing is performed */ ... signal(rw_mutex); } while (true); • The structure of a reader process do {wait(mutex);read_count++; if (read_count == 1) wait(rw_mutex); signal(mutex); ... /* reading is performed */ ... wait(mutex); read count--; if (read_count == 0) signal(rw_mutex); signal(mutex); } while (true); • W1과 R1 R2 R3… 상황에서,W1이 starvation이 되는 것을 방지함 • 이를 위해, writer에 rw_mutex semaphore를 사용하고, • 또한, 임계 구역에 진입하는 첫번째 reader( if(read_count==1))와 임계 구역을 빠져나오는 마지막 하나 남은 reader(if (read_count==0))에서만 rw_mutex를 쓸 수 있도록 함 • 즉, R2, R3, R4,…는 W1과 경쟁하지 못하게 하여 W1이 starvation 되는 상황 없앰

  40. Readers-Writers Problem Variations • Starvation problem is solved on some systems by providing reader-writer locks • The readers–writers problem and its solutions have been generalized to provide reader–writer locks on some systems. • Acquiring a reader–writer lock requires specifying the mode of the lock: either read or write access. • When a process wishes only to read shared data, it requests the reader–writer lock in read mode. • A process wishing to modify the shared data must request the lock in write mode. • Multiple processes are permitted to concurrently acquire a reader–writer lock in read mode, but only one process may acquire the lock for writing, as exclusive access is required for writers. • Reader–writer locks are most useful in the following situations: • shared data를 읽기만 하는 프로세스와 쓰기만 하는 프로세스를 식별하기 쉬운 응용 • Write보다 reader 개수가 많은 응용 ( This is because reader– writer locks generally requiremore overhead to establish than semaphores or mutual-exclusion locks. The increased concurrency of allowing multiple readers compensates for the overhead involved in setting up the reader–writer lock. )

  41. Dining-Philosophers Problem • Philosophers spend their lives alternating thinking and eating • When a philosopher thinks, she does not interact with her colleagues. • From time to time, a philosopher gets hungry and tries to pick up the two chopsticks that are closest to her (the chopsticks that are between her and her left and right neighbors) • A philosopher may pick up only one chopstick at a time. Obviously, she cannot pick up a chopstick that is already in the hand of a neighbor. When a hungry philosopher has both her chopsticks at the same time, she eats without releasing the chopsticks. When she is finished eating, she puts down both chopsticks and starts thinking again. • In the case of 5 philosophers • Shared data • Bowl of rice (data set) • 5 Semaphores : chopstick [5] initialized to 1 5 single chopsticks

  42. Dining-Philosophers Problem Algorithm c[4] • The structure of Philosopher i: do { wait (chopstick[i] ); wait (chopStick[ (i + 1) % 5] ); // eat signal (chopstick[i] ); signal (chopstick[ (i + 1) % 5] ); // think } while (TRUE); • What is the problem with this algorithm? c[3] c[5] 2 5 c[2] c[1] 1 • 인접한 두 철학자가 동시에 식사하지 않음을 보장하지만, deadlock 발생 • 5명의 philosopher가 동시에 배가 고픈 경우: • 자신의 left chopstick을 먼저 잡으면, 해당 chopstick semaphore는 모두 0이 되어, 각 philosopher는 오른쪽 chopstick을 잡기 위해 영원히 기다려야 함 (deadlock)

  43. Dining-Philosophers Problem Algorithm (Cont.) • Deadlock handling • Allow at most 4 philosophers to be sitting simultaneously at the table. • Allow a philosopher to pick up chopsticks only if both are available (picking must be done in a critical section. • Use an asymmetric solution -- an odd-numbered philosopher picks up first the left chopstick and then the right chopstick. Even-numbered philosopher picks up first the right chopstick and then the left chopstick.

  44. Problems with Semaphores • Incorrect use of semaphore operations: • signal (mutex) …. wait (mutex) • wait (mutex) … wait (mutex) • Omitting of wait (mutex) or signal (mutex) (or both) • Deadlock and starvation are possible.

  45. Monitors • A high-level abstraction that provides a convenient and effective mechanism for process synchronization • Abstract data type, internal variables only accessible by code within the procedure • Only one process may be active within the monitor at a time monitor monitor-name { // shared variable declarations procedure P1 (…) { …. } procedure Pn (…) {……} Initialization code (…) { … } } }

  46. Monitor Characteristics Reference: OS Design by Stallings

  47. Synchronization • Achieved by the use of condition variables that are contained within the monitor and accessible only within the monitor • Condition variables are operated on by two functions: • cwait(c): suspend execution of the calling process on condition c • csignal(c): resume execution of some process blocked after a cwait on the same condition Reference: OS Design by Stallings

  48. 모니터에는 특정 시점에 하나의 프로세스만 진입할 수 있음 • 모니터가 한 프로세스에의해 사용 중이면, 다른 프로세스는 “queue of entering process”에 queue됨 • 모니터 내부에서 수행 중이던 프로세스가 조건 c1에서 잠시 대기할 필요있으면, cwait(c1)을 호출함  c1 queue에서 block됨 • 조건이 변하면 blocked된 프로세스는 깨어나서 monitor에 재진입하고 cwait(c1) 이후 수행 • 모니터 내부에서 수행 중이던 프로세스가 조건 c1의 변화를 발견하면, csignal(c1)을 호출함 • 이는 c1 queue에서 대기중이던 프로세스를 깨움 • urgent queue는 monitor에서 수행되던 프로세스가 블록될 경우, 새로 진입하는 프로세스(queue of enterping processes)보다 더 높은 우선 순위를 갖고 다시 실행되기 위해 사용 가능

  49. A Solution to the Bounded-Buffer Producer/Consumer Problem Using a Monitor • Buffer 접근 제어를 위해 cond data type으로 선언된 notfull과 notempty 있음 • notfull: buffer에 데이터 저장할 공간남아 있는 경우 • notempty: buffer에 읽을 데이터가 있는 경우 (2) • (1) Producer는 monitor의 append를 호출하여, 데이터를 buffer에 추가 가능함 • (2) notfull일 경우에 진행. 만약 Full이면 cwait함  이때 다른 프로세스가 monitor에 들어갈 수 있음 • cwait에 의해 일시 중지 상태인 프로세스는 notfull 이 될 경우, 다시깨어나서 실행 재개함 • 버퍼에데이터씀 (3) (3) consumer는 buffer가 notempty일때 읽음. 읽은 후에 waiting 중인 producer가 받을 수 있는 signal(notfull)을 발생함. waiting 중인 Producer가 있으면 buffer가 notfull 이라는 signal을 받았으므로 새로운 데이터를 쓸 수 있게 됨 (1)

  50. Reference: OS Design by Stallings

More Related