1 / 105

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization. Module 6: Process Synchronization. Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization Examples Atomic Transactions. Background.

dawson
Télécharger la présentation

Chapter 6: Process Synchronization

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. Module 6: Process Synchronization • Background • The Critical-Section Problem • Peterson’s Solution • Synchronization Hardware • Semaphores • Classic Problems of Synchronization • Monitors • Synchronization Examples • Atomic Transactions

  3. Background • Concurrent access to shared data may result in data inconsistency • Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes • Suppose that we wanted to provide a solution to the consumer-producer problem that fills all the buffers. • Use an integer count that keeps track of the number of full buffers. • Initially, count is 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.

  4. Producer while (true) /* produce an item and put in nextProduced while (count == BUFFER_SIZE) ; // do nothing buffer [in] = nextProduced; in = (in + 1) % BUFFER_SIZE; count++; }

  5. Consumer while (1) { while (count == 0) ; // do nothing nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; /* consume the item in nextConsumed }

  6. Race Condition • count++ could be implemented asregister1 = count register1 = register1 + 1 count = register1 • count-- could be implemented asregister2 = count register2 = register2 - 1 count = register2 • Consider this execution interleaving with “count = 5” initially: S0: producer execute register1 = count {register1 = 5}S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = count {register2 = 5} S3: consumer execute register2 = register2 - 1 {register2 = 4} S4: producer execute count = register1 {count = 6 } S5: consumer execute count = register2 {count = 4}

  7. Solution to Critical-Section Problem 1. Mutual Exclusion - If process Pi is executing in its critical section, then no other processes can be executing in their critical sections 2. 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 3. 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 • Assume that each process executes at a nonzero speed • No assumption concerning relative speed of the N processes

  8. Peterson’s Solution • Two process solution • Assume that the LOAD and STORE 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 flag array is used to indicate if a process is ready to enter the critical section. flag[i] = true implies that process Pi is ready!

  9. Algorithm for Process Pi do { flag[i] = TRUE; turn = j; while ( flag[j] && turn == j); CRITICAL SECTION flag[i] = FALSE; REMAINDER SECTION } while (TRUE);

  10. Synchronization Hardware • Many systems provide hardware support for critical section code • Uniprocessors – could disable interrupts • Currently running code would execute without preemption • Generally too inefficient on multiprocessor systems • Operating systems using this not broadly scalable • Modern machines provide special atomic hardware instructions • Atomic = non-interruptable • Either test memory word and set value • Or swap contents of two memory words

  11. TestAndndSet Instruction • Definition: boolean TestAndSet (boolean *target) { boolean rv = *target; *target = TRUE; return rv: }

  12. Data Register CC Register The memory location is always set to TRUE TS is a single machine instruction. It cannot be interrupted. R3 FALSE =0 m TRUE Primary Memory (b) After Executing TS Implementing Semaphores:Test and Set Instruction • TS R3, m ;test-and-set of location m • TS(m): [Reg_i = memory[m]; memory[m] = TRUE; CC = value(Reg_i);] Data Register ConditionCode Register R3 … … m FALSE Primary Memory • Before Executing TS

  13. Solution using TestAndSet • Shared boolean variable lock., initialized to false. • Solution: do { while ( TestAndSet (&lock )) ; /* do nothing // critical section lock = FALSE; // remainder section } while ( TRUE);

  14. Swap Instruction • Definition: void Swap (boolean *a, boolean *b) { boolean temp = *a; *a = *b; *b = temp: }

  15. Solution using Swap • Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key. • Solution: do { key = TRUE; while ( key == TRUE) Swap (&lock, &key ); // critical section lock = FALSE; // remainder section } while ( TRUE);

  16. Semaphore • Synchronization tool that does not require busy waiting • Implemented by the OS • Implemented without busy waiting • Semaphore S – integer variable • Two standard operations modify S: wait() and signal() • Originally called P() andV() • P(s): proberen, “to test” • V(s): verhogen, “to increment” or signal • Less complicated

  17. Semaphore Implementation with no Busy waiting(Cont.) • Implementation of wait with no busy waiting: wait (S){ value--; if (value < 0) { add this process to waiting queue block(); } } • Implementation of signal: Signal (S){ value++; if (value <= 0) { remove a process P from the waiting queue wakeup(P); } }

  18. Semaphore as General Synchronization Tool • Countingsemaphore – integer value can range over an unrestricted domain • Binary semaphore – integer value can range only between 0 and 1; can be simpler to implement • Also known as mutex locks • Can implement a counting semaphore S as a binary semaphore

  19. Using the TS Instruction Solution using TS Solution using semaphores boolean s = FALSE; . . . while(TS(s)) ; <critical section> s = FALSE; . . . semaphore s = 1; . . . wait(s) ; <critical section> signal(s); . . . The first process finds s to be FALSE. All remaining process find s to be TRUE until the first process executes s = FALSE

  20. Using the TS Instruction • The TS instruction can be used to implement the binary semaphore. • Can it be used for the general semaphore?

  21. Semaphore Implementation • Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time • Thus, implementation becomes the critical section problem where the wait and signal code are placed in the critical section. • Could now have busy waiting in 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.

  22. 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.

  23. Implementing the General Semaphore struct semaphore { int value = <initial value>; boolean mutex = FALSE; boolean hold = TRUE; }; shared struct semaphore s; wait(struct semaphore s) { while(TS(s.mutex)) ; s.value--; if(s.value < 0) ( s.mutex = FALSE; while(TS(s.hold)) ; } else s.mutex = FALSE; } Variable mutex ensures mutual exclusion in the CS. This while statement is necessary to prevent a race . The signaling process loops until another process does a P operation. signal(struct semaphore s) { while(TS(s.mutex)) ; s.value++; if(s.value <= 0) ( while(!s.hold) ; s.hold = FALSE; } s.mutex = FALSE; } When a process signals, the value is incremented. Variable hold causes processes to busy-wait if the semaphore is less than 0.

  24. Implementing the General Semaphore Solution without busy-waiting struct semaphore { int value = <initial value>; boolean mutex = FALSE; boolean hold = TRUE; }; shared struct semaphore s; wait(struct semaphore s) { while(TS(s.mutex)) yield (*, scheduler); s.value--; if(s.value < 0) ( s.mutex = FALSE; while(TS(s.hold)) yield (*, scheduler) ; } else s.mutex = FALSE; } When a process must wait, it yields the CPU. Uses the yield instruction from chapter 7. signal(struct semaphore s) { while(TS(s.mutex)) yield (*, scheduler); s.value++; if(s.value <= 0) ( while(!s.hold) yield (*, scheduler); s.hold = FALSE; } s.mutex = FALSE; }

  25. Active vs Passive Semaphores • A process can dominate the semaphore • Performs signal operation, but continues to execute • Performs another wait operation before releasing the CPU • Called a passive implementation of V • Active implementation calls scheduler as part of the V operation. • Changes semantics of semaphore! • Cause people to rethink solutions

  26. 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 and Q be 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.

  27. Classical Problems of Synchronization • Bounded-Buffer Problem • Readers and Writers Problem • Dining-Philosophers Problem

  28. Bounded Buffer Problem Empty Pool Producer Consumer Full Pool

  29. Bounded-Buffer Problem • use counting semaphores • they keep a count of the number of empty and full buffers • also synchronize the producer/consumer; • empty semaphore used to block producer if no empty buffers left • initialized to the value N. • full semaphore used to block consumer if no full buffers left • initialized to the value 0 • mutex semaphore protects CS where buffers are manipulated N buffers, each can hold one item • initialized to the value 1

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

  31. Bounded Buffer Problem (Cont.) • The structure of the consumer process do { wait (full); wait (mutex); // remove an item from buffer signal (mutex); signal (empty); // consume the removed item } while (true);

  32. Deadlock. Order matters! Bounded Buffer Problem (Unix) producer() { buf_type *next, *here; while(TRUE) { produce_item(next); /* Claim an empty */ P(empty); P(mutex); here = obtain(empty); V(mutex); copy_buffer(next, here); P(mutex); release(here, fullPool); V(mutex); /* Signal a full buffer */ V(full); } } semaphore mutex = 1; semaphore full = 0; /* A general (counting) semaphore */ semaphore empty = N; /* A general (counting) semaphore */ buf_type buffer[N]; fork(producer, 0); fork(consumer, 0); consumer() { buf_type *next, *here; while(TRUE) { /* Claim full buffer */ P(mutex); P(full); here = obtain(full); V(mutex); copy_buffer(here, next); P(mutex); release(here, emptyPool); V(mutex); /* Signal an empty buffer */ V(empty); consume_item(next); } }

  33. Bounded Buffer Problem (Unix) producer() { buf_type *next, *here; while(TRUE) { produce_item(next); /* Claim an empty */ P(empty); P(mutex); here = obtain(empty); V(mutex); copy_buffer(next, here); P(mutex); release(here, fullPool); V(mutex); /* Signal a full buffer */ V(full); } } semaphore mutex = 1; semaphore full = 0; /* A general (counting) semaphore */ semaphore empty = N; /* A general (counting) semaphore */ buf_type buffer[N]; fork(producer, 0); fork(consumer, 0); consumer() { buf_type *next, *here; while(TRUE) { /* Claim full buffer */ P(full); P(mutex); here = obtain(full); V(mutex); copy_buffer(here, next); P(mutex); release(here, emptyPool); V(mutex); /* Signal an empty buffer */ V(empty); consume_item(next); } }

  34. Readers-Writers Problem • A data set is shared among a number of concurrent processes • Readers – only read the data set; they do not perform any updates • Writers – can both read and write. • Problem – allow multiple readers to read at the same time. Only one single writer can access the shared data at the same time. • Shared Data • Data set • Semaphore mutex initialized to 1. • Semaphore wrt initialized to 1. • Integer readcount initialized to 0.

  35. Readers-Writers Problem (Cont.) • The structure of a writer process do { wait (wrt) ; // writing is performed signal (wrt) ; } while (true)

  36. Readers-Writers Problem (Cont.) • The structure of a reader process do { wait (mutex) ; readcount ++ ; if (readercount == 1) wait (wrt) ; signal (mutex) // reading is performed wait (mutex) ; readcount - - ; if redacount == 0) signal (wrt) ; signal (mutex) ; } while (true)

  37. First reader competes with writers • Last reader signals writers • Readers have priority over writers First Unix Solution reader() { while(TRUE) { <other computing>; P(mutex); readCount++; if(readCount == 1) P(writeBlock); V(mutex); /* Critical section */ access(resource); P(mutex); readCount--; if(readCount == 0) V(writeBlock); V(mutex); } } resourceType *resource; int readCount = 0; semaphore mutex = 1; semaphore writeBlock = 1; fork(reader, 0); fork(writer, 0); writer() { while(TRUE) { <other computing>; P(writeBlock); /* Critical section */ access(resource); V(writeBlock); } }

  38. First Solution (2) reader() { while(TRUE) { <other computing>; P(mutex); readCount++; if(readCount == 1) P(writeBlock); V(mutex); /* Critical section */ access(resource); P(mutex); readCount--; if(readCount == 0) V(writeBlock); V(mutex); } } resourceType *resource; int readCount = 0; semaphore mutex = 1; semaphore writeBlock = 1; fork(reader, 0); fork(writer, 0); writer() { while(TRUE) { <other computing>; P(writeBlock); /* Critical section */ access(resource); V(writeBlock); } } • First reader competes with writers • Last reader signals writers • Any writer must wait for all readers • Readers can starve writers • “Updates” can be delayed forever • May not be what we want

  39. 3 2 1 Writer Precedence (Unix) reader() { while(TRUE) { <other computing>; P(readBlock); P(mutex1); readCount++; if(readCount == 1) P(writeBlock); V(mutex1); V(readBlock); access(resource); P(mutex1); readCount--; if(readCount == 0) V(writeBlock); V(mutex1); } } int readCount = 0, writeCount = 0; semaphore mutex = 1, mutex2 = 1; semaphore readBlock = 1, writeBlock = 1, writePending = 1; fork(reader, 0); fork(writer, 0); writer() { while(TRUE) { <other computing>; P(mutex2); writeCount++; if(writeCount == 1) P(readBlock); V(mutex2); P(writeBlock); access(resource); V(writeBlock); P(mutex2) writeCount--; if(writeCount == 0) V(readBlock); V(mutex2); } } First Writer does a P(readBlock) to block any new readers

  40. 4 3 2 1 Writer Precedence (in Unix) reader() { while(TRUE) { <other computing>; P(readBlock); P(mutex1); readCount++; if(readCount == 1) P(writeBlock); V(mutex1); V(readBlock); access(resource); P(mutex1); readCount--; if(readCount == 0) V(writeBlock); V(mutex1); } } int readCount = 0, writeCount = 0; semaphore mutex = 1, mutex2 = 1; semaphore readBlock = 1, writeBlock = 1, writePending = 1; fork(reader, 0); fork(writer, 0); writer() { while(TRUE) { <other computing>; P(mutex2); writeCount++; if(writeCount == 1) P(readBlock); V(mutex2); P(writeBlock); access(resource); V(writeBlock); P(mutex2) writeCount--; if(writeCount == 0) V(readBlock); V(mutex2); } } Next reader is blocked because the first writer did a P(readBlock) Writer blocks on P(writeBlock)

  41. 4 3 2 1 Last reader signals writer to begin Writer Precedence (in Unix) reader() { while(TRUE) { <other computing>; P(readBlock); P(mutex1); readCount++; if(readCount == 1) P(writeBlock); V(mutex1); V(readBlock); access(resource); P(mutex1); readCount--; if(readCount == 0) V(writeBlock); V(mutex1); } } int readCount = 0, writeCount = 0; semaphore mutex = 1, mutex2 = 1; semaphore readBlock = 1, writeBlock = 1, writePending = 1; fork(reader, 0); fork(writer, 0); writer() { while(TRUE) { <other computing>; P(mutex2); writeCount++; if(writeCount == 1) P(readBlock); V(mutex2); P(writeBlock); access(resource); V(writeBlock); P(mutex2) writeCount--; if(writeCount == 0) V(readBlock); V(mutex2); } }

  42. 4 3 5 Writer Precedence (2) reader() { while(TRUE) { <other computing>; P(writePending); P(readBlock); P(mutex1); readCount++; if(readCount == 1) P(writeBlock); V(mutex1); V(readBlock); V(writePending); access(resource); P(mutex1); readCount--; if(readCount == 0) V(writeBlock); V(mutex1); } } int readCount = 0, writeCount = 0; semaphore mutex = 1, mutex2 = 1; semaphore readBlock = 1, writeBlock = 1, writePending = 1; fork(reader, 0); fork(writer, 0); writer() { while(TRUE) { <other computing>; P(mutex2); writeCount++; if(writeCount == 1) P(readBlock); V(mutex2); P(writeBlock); access(resource); V(writeBlock); P(mutex2) writeCount--; if(writeCount == 0) V(readBlock); V(mutex2); } } Any new reader must wait until the last writer signals Any new writer has priority over any waiting reader but is stuck until first writer is finished

  43. Writer Precedence (2) • Any writer must wait for current readers to finish • Any writer has priority over any new readers • The writers can starve readers • “Reads” can be delayed forever • May not be what we want

  44. Dining-Philosophers Problem • Shared data • Bowl of rice (data set) • Semaphore chopstick [5] initialized to 1

  45. Dining-Philosophers Problem (Cont.) • 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) ; Deadlock! Where? Will see a solution in monitors later.

  46. 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)

  47. the body of every public function is surrounded by the same mutex semaphore Monitors • An attempt to provide better tools for synchronization problems • Specialized form of ADT • Encapsulates implementation • Public interface (types & functions) • Only one process can be executing in the ADT at a time • other processes that try to use the monitor are forced to wait monitor anADT { semaphore mutex = 1; // Implicit . . . public: proc_i(…) { P(mutex); // Implicit <processing for proc_i>; V(mutex); // Implicit }; . . . }; Conceptually how monitors are implemented. Actual implementations vary

  48. Monitors • Only one process may be active within the monitor at a time monitor monitor-name { // shared variable declarations procedure P1 (…) { …. } … procedure Pn (…) {……} Initialization code ( ….) { … } … } }

  49. Schematic view of a Monitor

  50. Example1: Shared Balance programmer does not have to use semaphores; only one process can be in any function of the monitor at a time. Implicit semaphores are added by the compiler. monitor sharedBalance { double balance; public: credit(double amount) {balance += amount;}; debit(double amount) {balance -= amount;}; . . . }; In process 1 code: …sharedBalance.credit(100); In process 2 code: … sharedBalance.debit(50);

More Related