Set4(Synchronization)
3 Pages

Set4(Synchronization)

Course Number: CSE 410, Fall 2009

College/University: Texas A&M

Word Count: 2549

Rating:

Document Preview

CPSC-410/611 Operating Systems Process Synchronization Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems Process Management: Synchronization Why? How? Examples...

Unformatted Document Excerpt
Coursehero >> Texas >> Texas A&M >> CSE 410

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Operating CPSC-410/611 Systems Process Synchronization Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems 1 CPSC-410/611 Operating Systems Process Synchronization The Critical Section Problem: Example 1 void echo() { input(in, keyboard); out := in; output(out, display); } Process 1 Echo() input(in,keyboard) out = in; input(in,keyboard); out = in; output(out,display); char in; /* shared variables */ char out; Operation: Interleaved execution Process 2 Echo() output(out,display) Race condition ! The Critical Section Problem: Example 2 Producer-consumer with bounded, shared-memory, buffer. out circular buffer of size n int Item int in, out; buffer[n]; counter; in Producer: void deposit(Item * next) { while (counter == n) no_op; buffer[in] = next; in = (in+1) MOD n; counter = counter + 1; } Consumer: Item * remove() { while (counter == 0) no_op; next = buffer[out]; out = (out+1) MOD n; counter = counter - 1; return next; } 2 CPSC-410/611 Operating Systems Process Synchronization This Implementation is not Correct! Producer operation: on CPU: counter = counter + 1 reg1 = counter reg1 = reg1 + 1 counter = reg1 reg1 = counter reg1 = reg1 + 1 reg2 = counter reg2 = reg2 - 1 counter = reg1 counter = reg2 Race condition! Need to ensure that only one process can manipulate variable counter at a time : synchronization. Consumer counter = counter - 1 reg2 = counter reg2 = reg2 - 1 counter = reg2 interleaved execution: Critical Section Problem: Example 3 Insertion of an element into a list. new curr prev next prev next prev next 1. new curr prev next prev next prev next void insert(new, curr) { /*1*/ new.next = curr.next; /*2*/ new.prev = c.next.prev; /*3*/ curr.next = new; /*4*/ new.next.prev = new; } new curr prev next prev next prev 2. new curr prev next prev next prev next new curr 4. prev next prev next 3. prev next next 3 CPSC-410/611 Operating Systems Process Synchronization Interleaved Execution causes Errors! Process 1 new1.next = curr.next; new1.prev = c.next.prev; ... ... ... ... curr.next = new1; new.next.prev = new1; new1 curr prev next new2 next Process 2 ... ... new2.next = curr.next; new2.prev = c.next.prev; curr.next = new2; new.next.prev = new2; ... ... prev prev next prev next Must guarantee mutually exclusive access to list data structure! Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems 4 CPSC-410/611 Operating Systems Process Synchronization Critical Sections Execution of critical section by processes must be mutually exclusive. Typically due to manipulation of shared variables. Need protocol to enforce mutual exclusion. while (TRUE) { enter section; critical section; exit section; remainder section; } Criteria for a Solution of the C.S. Problem 1. Only one process at a time can enter the critical section. 2. A process that halts in non-critical section cannot prevent other processes from entering the critical section. 3. A process requesting to enter a critical section should not be delayed indefinitely. 4. When no process is in a critical section, any process that requests to enter the critical section should be permitted to enter without delay. 5. Make no assumptions about the relative speed of processors (or their number). 6. A process remains within a critical section for a finite time only. 5 CPSC-410/611 Operating Systems Process Synchronization A (Wrong) Solution to the C.S. Problem Two processes P0 and P1 int turn; /* turn == i : Pi is allowed to enter c.s. */ Pi: while (TRUE) { while (turn != i) no_op; critical section; turn = j; remainder section; } Another Wrong Solution bool flag[2]; /* initialize to FALSE */ /* flag[i] == TRUE : Pi intends to enter c.s.*/ Pi: while (TRUE) { while (flag[j]) no_op; flag[i] = TRUE; critical section; flag[i] = FALSE; remainder section; } 6 CPSC-410/611 Operating Systems Process Synchronization Yet Another Wrong Solution bool flag[2]; /* initialize to FALSE */ /* flag[i] == TRUE : Pi intends to enter c.s.*/ while (TRUE) { flag[i] = TRUE; while (flag[j]) no_op; critical section; flag[i] = FALSE; remainder section; } A Combined Solution (Petersen) int turn; bool flag[2]; /* initialize to FALSE */ while (TRUE) { flag[i] = TRUE; turn = j; while (flag[j]) && (turn == j) no_op; critical section; flag[i] = FALSE; remainder section; } 7 CPSC-410/611 Operating Systems Process Synchronization Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems Hardware Support For Synchronization Disallow interrupts simplicity widely used problem: interrupt service latency problem: what about multiprocessors? Atomic operations: Operations that check and modify memory areas in a single step (i.e. operation can not be interrupted) Test-And-Set Exchange, Swap, Compare-And-Swap 8 CPSC-410/611 Operating Systems Process Synchronization Test-And-Set bool TestAndSet(bool & var) { bool temp; temp = var; bool lock; /* init to FALSE */ var = TRUE; return temp; while (TRUE) { } while (TestAndSet(lock)) no_op; critical section; lock = FALSE; remainder section; } atomic! Mutual Exclusion with Test-And-Set Exchange (Swap) void Exchange(bool & a, bool & b){ bool temp; bool lock; /*init to FALSE */ temp = a; a = b; while (TRUE) { b = temp; } dummy = TRUE; do Exchange(lock, dummy); while(dummy); critical section; lock = FALSE; remainder section; } atomic! Mutual Exclusion with Exchange 9 CPSC-410/611 Operating Systems Process Synchronization Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems Semaphores Problems with solutions above: Although requirements simple (mutual exclusion), addition to programs complex. Based on busy waiting. A Semaphore variable has two operations: V(Semaphore * s); /* Increment value of s by 1 in a single indivisible action. If value is not positive, then a process blocked by a P is unblocked*/ P(Semaphore * s); /* Decrement value of s by 1. If the value becomes negative, the process invoking the P operation is blocked. */ Binary semaphore: The value of s can be either 1 or 0 (TRUE or FALSE). General semaphore: The value of s can be any integer. 10 CPSC-410/611 Operating Systems Process Synchronization Effect of Semaphores Synchronization using semaphores: s.value = 0 P(s) V(s) Mutual exclusion with semaphores: BinSemaphore * s; /* init to TRUE*/ while (TRUE) { P(s); critical section; V(s); P(s) V(s) remainder section; } Implementation (with busy waiting) Binary Semaphores: P(BinSemaphore * s) { key = FALSE; do exchange(s.value, key); while (key == FALSE); } V(BinSemaphore * s) { s.value = TRUE; } General Semaphores: BinSemaphore * mutex /*TRUE*/ BinSemaphore * delay /*FALSE*/ P(Semaphore * s) { P(mutex); s.value = s.value - 1; if (s.value < 0) { V(mutex); P(delay); } else V(mutex); } V(Semaphore * s) { P(mutex); s.value = s.value + 1; if (s.value <= 0) V(delay); V(mutex); } 11 CPSC-410/611 Operating Systems Process Synchronization Implementation ("without" busy waiting) Semaphore bool lock; /* init to FALSE */ int value; PCBList * L; blocked processes P(Semaphore * s) { while (TestAndSet(lock)) no_op; s.value = s.value - 1; if (s.value < 0) { append(this_process, s.L); lock = FALSE; sleep(); } lock = FALSE; } V(Semaphore * s) { while (TestAndSet(lock)) no_op; s.value = s.value + 1; if (s.value <= 0) { PCB * p = remove(s.L); wakeup(p); } lock = FALSE; } Problems with Semaphores Deadlocks: Process is blocked waiting for an event only it can generate. P P 1 2 s.value = 1 q.value = 1 P(s) P(q) ... V(s) V(q) P(q) P(s) ... V(q) V(s) 12 CPSC-410/611 Operating Systems Process Synchronization Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores More sophisticated synchronization mechanisms: Monitors, Message Passing Classical synchronization problems Classical Problems: Producer-Consumer Semaphore * n; /* initialized to 0 */ BinSemaphore * mutex; /* initialized to TRUE */ Producer: while (TRUE) { produce item; P(mutex); Consumer: while (TRUE) { P(n); P(mutex); remove item; deposit item; V(mutex); V(mutex); V(n); } } consume item; 13 CPSC-410/611 Operating Systems Process Synchronization Producer-Consumer with Bounded Buffer Semaphore * full; /* initialized to 0 */ Semaphore * empty; /* initialized to n */ BinSemaphore * mutex; /* initialized to TRUE */ Classical Problems: Producer: while (TRUE) { produce item; P(mutex); P(empty); deposit item; V(mutex); V(full); } Consumer: while (TRUE) { P(full); P(mutex); remove item; V(mutex); V(empty); consume item; } Dining Philosophers 5 philosophers around a table, a plate in front of each philosopher, one chopstick between any two plates. When philosopher get hungry, he must grab both chopsticks in order to be able to eat. Semaphore * chopstick[4]; /* initialize to 1 */ while (TRUE) { P(chopstick[i]); P(chopstick[(i+1) mod 5]); eat ... V(chopstick[i]); V(chopstick[(i+1) mod 5]); think ... } Classical Problems: Problem: deadlock 14 CPSC-410/611 Operating Systems Process Synchronization The Barbershop barber shop (capacity 20) Classical Problems: cashier barber chairs (3) entry door standing room area sofa (capacity 4) exit door Semaphore * max_capacity; /* init to 20 */ Semaphore * sofa; /* init to 4 */ Semaphore * barber_chair; /* init to 3 */ Semaphore * coord; /* init to 3 */ Semaphore * cust_ready; /* init to 0 */ Semaphore * leave_b_chair; /* init to 0 */ Semaphore * payment; /* init to 0 */ Semaphore * receipt; /* init to 0 */ The Barbershop (cont) Process customer: P(max_capacity); <enter shop> P(sofa); <sit on sofa> P(barber_chair); <get up from sofa> V(sofa); <sit in barber chair> V(cust_ready); P(finished); <leave barber chair> V(leave_b_chair); <pay> V(payment); P(receipt); <exit shop> V(max_capacity); Process cashier: for(;;){ P(payment); P(coord); <accept pay> V(coord); V(receipt); } Process barber: for(;;){ P(cust_ready); P(coord); <cut hair> V(coord); V(finished); P(leave_b_chair); V(barber_chair); } 15 CPSC-410/611 Operating Systems Process Synchronization Process customer: P(max_capacity); <enter shop> P(mutex1); custnr := ++count; V(mutex1); P(sofa); <sit on sofa> P(barber_chair); <get up from sofa> V(sofa); <sit in barber chair> P(mutex2); enqueue(custnr); V(cust_ready); V(mutex2); P(finished[custnr]); <leave barber chair> V(leave_b_chair); <pay> V(payment); P(receipt); <exit shop> V(max_capacity); The Fair Barbershop Process cashier: for(;;){ P(payment); P(coord); <accept pay> V(coord); V(receipt); } Process barber: for(;;){ P(cust_ready); P(mutex2); dequeue(b_cust); V(mutex2); P(coord); <cut hair> V(coord); V(finished[b_cust]); P(leave_b_chair); V(barber_chair); } Classical Problems: Readers/Writers Multiple readers can access data element concurrently. Writers access data element exclusively. Semaphore * mutex, * wrt; int nreaders; /* initialized to 1 */ /* initialized to 0 */ Reader: P(mutex); nreaders = nreaders + 1; if (nreaders == 1) P(wrt); V(mutex); do the reading .... P(mutex); nreaders = nreaders - 1; if (nreaders = 0) V(wrt); V(mutex); Writer: P(wrt); do the writing ... V(wrt); 16 CPSC-410/611 Operating Systems Process Synchronization Incorrect Implementation of Readers/Writers monitor ReaderWriter{ int numberOfReaders = 0; int numberOfWriters = 0; boolean busy = FALSE; /* READERS */ procedure startRead() { while (numberOfWriters != 0); numberOfReaders = numberOfReaders + 1; } procedure finishRead() { numberOfReaders = numberOfReaders - 1; } /* WRITERS */ procedure startWrite() { numberOfWriters = numberOfWriters + 1; while (busy || (numberOfReaders > 0)); busy = TRUE; }; procedure finishWrite() { numberOfWriters = numberOfWriters - 1; busy = FALSE; }; }; A Correct Implementation monitor ReaderWriter{ int numberOfReaders = 0; int numberOfWriters = 0; boolean busy = FALSE; condition okToRead, okToWrite; /* READERS */ procedure startRead() { if (busy || (okToWrite.lqueue)) okToRead.wait; numberOfReaders = numberOfReaders + 1; okToRead.signal; } procedure finishRead() { numberOfReaders = numberOfReaders - 1; if (numberOfReaders = 0) okToWrite.signal; } /* WRITERS */ procedure startWrite() { if (busy || (numberOfReaders > 0)) okToWrite.wait; busy = TRUE; }; procedure finishWrite() { busy = FALSE; if (okToWrite.lqueue) okToWrite.signal; else okToRead.signal; }; }; 17 CPSC-410/611 Operating Systems Process Synchronization Process Management: Synchronization Why? How? Examples Software solutions Hardware-supported solutions What? The Critical Section Problem The basic synchronization mechanism: Semaphores Classical synchronization problems More sophisticated synchronization mechanisms: Monitors, Message Passing Higher-Level Synchronization Primitives Semaphores as the "GOTO" among the synchronization primitives. very powerful, but tricky to use. Need higher-abstraction primitives, for example: Monitors synchronized primitive in JAVA Protected Objects (Ada95) Conditional Critical Regions Message Passing 18 CPSC-410/611 Operating Systems Process Synchronization Monitors (Hoare / Brinch Hansen, 1973) Safe and effective sharing of abstract data types among several processes. Monitors can be modules, or objects. local variable accessible only through monitor's procedures process can entrer monitor only by invoking monitor procedure Only one process can be active in monitor. Additional synchronization through conditions (similar to semaphores) Condition c; c.cwait() : suspend execution of calling process and enqueue it on condition c. The monitor now is available for other processes. c.csignal() : resume a process enqueued on c. If none is enqueued, do nothing. cwait/csignal different from P/V: cwait always waits, csignal does nothing if nobody waits. Structure of Monitor local (shared) data c1 procedure 1 procedure 2 ... cm urgent queue procedure k operations initialization code blocked processes ... 19 CPSC-410/611 Operating Systems Process Synchronization Example: Binary Semaphore monitor BinSemaphore { bool condition locked; /* Initialize to FALSE */ idle; entry void P() { if (locked) idle.cwait(); locked = TRUE; } entry void ...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Texas A&M - CSE - 410
CPSC-410/611 Operating SystemsExceptions, MIPS-Style Reminder: MIPS CPU deals with exceptions. Interrupts are just a special case of exceptions. The MIPS Architecture has no interrupt-vector table! All exceptions trigger a jump to the same loc
Texas A&M - CSE - 410
CPSC 410 / 611 : Operating SystemsCPU Scheduling Schedulers in the OS Structure of a CPU Scheduler Scheduling = Selection + Dispatching Criteria for scheduling Scheduling Algorithms FIFO/FCFS SPF / SRTF Priority / MLFQ Thread Dispatching
Texas A&M - CSE - 410
CPSC-410/611 Operating SystemsDeadlocksDeadlocks The Deadlock Problem Examples Interlude on Mars Resource and system model, and exact definitions Solutions: Prevention Avoidance Detection and recovery Reading: Silberschatz, Chapter 7T
Texas A&M - CSE - 410
CPSC 410/611: Operating SystemsProjects, Introduction+Projects: Developing an OS Kernel for x86Introduction+Overview! ! ! ! !Platform and Development Environment (tentative) The boot process Multi-boot compliant code The main() function
Oakland University - CSE - 40244
SAGE ANNUAL SALARY SURVEY FOR 2007Published August 13, 2008 2008 The USENIX Association, All Rights ReservedMembers may print and share up to five copies of this document.Table of ContentsIntroduction .. 1 A Note on Nomenclature . 1 Summary .
Oakland University - CSE - 30341
CSE 30341: Quiz 2 (5 minutes)Individual effort. Closed books, notes, etc. 1. Deadlock can arise if four conditions hold simultaneously: a. Mutual exclusion: only one process at a time can use a resource. b. Hold and wait: a process holding at least
Oakland University - CSE - 40373
An Experimental Study of the Skype Peer-to-Peer VoIP SystemSaikat Guha (Cornell) Neil Daswani (Google) Ravi Jain (Google)IPTPS 2006Saikat Guha, Neil Daswani, Ravi JainExperimental Study of SkypeAbout SkypeVoice over IP (VoIP) 50 million use
Oakland University - CSE - 30341
Some clarifications about OS OS role: Properly functioning OS ensures that protection between processes are not breached. OS makes no such promise for threads within a single process. Two processes cannot share memory unless explicitly allowed. Tw
Oakland University - CSE - 30341
Operating Systems: Hollistic view Operational States Startup / Boot strap process Manage resources in the steady state Processes/threads/synchronization Memory/VM/swap File system/storage Functionality Hardware support required to perform me
Oakland University - CSE - 30341
CPU Scheduling: Basic Concepts Maximum CPU utilization obtained with multiprogramming - several processes are kept in memory, while one is waiting for I/O, the OS gives the CPU to another process OS does CPU scheduling CPU scheduling depends on t
Oakland University - CSE - 30341
Page Replacement3/9/07CSE 30341: Operating Systems Principlespage 1Page Replacement Algorithms Want lowest page-fault rate Evaluate algorithm by running it on a particular string of memory references (reference string) and computing the num
Oakland University - CSE - 30341
Tape pictures4/11/07CSE 30341: Operating Systems Principlespage 1Tape Drives The basic operations for a tape drive differ from those of a disk drive. locate positions the tape to a specific logical block, not an entire track (corresponds to
Oakland University - CSE - 30341
Locking protocol to enforce order Shared: Transaction can read but not write Exclusive: Transaction can read and write Two phase protocol to ensure serializability: Growing phase - transaction can obtain but not release locks Shrinking phase - t
Oakland University - CSE - 40373
CSE 4/60373: Multimedia Systems So far Multimedia Coding Multimedia systems issues on providing QoS across disk/network/OS etc. Outline for today Chapter 8: Synchronization (Section 8.1 thru 8.5) Synchronization is the harder component - essen
Oakland University - CSE - 30341
Thrashing If a process does not have enough pages, the page-fault rate is very high. This leads to: low CPU utilization operating system thinks that it needs to increase the degree of multiprogramming because of low cpu utilization another proces
Oakland University - CSE - 40463
A Performance and Schedulability Analysis of an Autonomous Mobile RobotAla Qadi Steve Goddard Computer Science &amp; Engineering University of NebraskaLincoln Lincoln, NE 68588-0115 {aqadi, goddard}@cse.unl.eduAbstract We present an autonomous, mobile,
Texas A&M - CPSC - 438
Evaluating Enterprise Portal Development ToolsExecutive SummaryEnterprise Information Portals (EIP) are gaining the attention of many senior corporate executives as a way to visualize real-time operational data as it relates to their individual ro
Texas A&M - CPSC - 438
The SGML Technologies GroupThis is the Group with: US $30,000,000 cumulative value of SGML projects; 300 years of cumulative experience in SGML. Formation of the SGML Technologies Group The SGML Technologies Group is a pan-European group of compan
Texas A&M - CPSC - 438
F2PS - The Fast Form Printing SystemMost solutions for automating the printing of forms and other types of commercial documents are based on one of two solutions: using word processing programs that offer the comfort of a WYSIWYG editor, usually c
Texas A&M - CPSC - 438
SigmaLinkThe Intranet Based Document Management and Editorial System with full SGML and XML Support Petra Leuser, Tibor Tscheke STEP Electronic Publishing Solutions GmbH Overview 1. 2. 2.1 2.2 3. 3.1 3.2 4. 4.1 4.2 4.3 5. 5.1 6. 6.1 6.2 7. 8. 8.1 9.
Texas A&M - CPSC - 438
Some of Our ProjectsBanking and Other Financial Institutions Analysis, partial implementation, and project management of an imaging and workflow application. This was to automate and improve the provision of a bank's cost statements (including invo
Texas A&M - CPSC - 438
Press Release from STEP GmbHRimpar, June 23, 1999STEP Group forms new company in the United Kingdom STEP GmbH is pleased to announce the formation of a new company based in the UK. The company will be based in Swindon and starts operations on Jul
Texas A&M - CPSC - 438
SGMLC - The SGML ComposerSGMLC is a full programming language designed for processing SGML/XML documents on Microsoft Windows platforms (Windows 3.11, 95, or NT4). It can be used to create: interactive conversion applications - where an SGML/XM
Texas A&M - CPSC - 438
VISUAL SGML - The SGML Integrated ToolkitVISUAL SGML is designed to make developing an advanced SGML application as easy as developing any other IT application. By providing all the tools an application developer needs in a single, fully-integrated
Texas A&M - CPSC - 438
file:/UntitledXML Tutorials for Programmers Ralf I. Pfeiffer IBM XML Technology Group Tutorial 2: Writing XML Documents What does XML do for data? If I know HTML, do I know XML? Some major differences between HTML and XML Some minor differences bet
Texas A&M - CPSC - 438
file:/UntitledEducation: PapersBuilding an XML application, step 1: Writing a DTD Doug Tidwell IBM XML Technical Strategy Group, TaskGuide Development Updated January 1999 Step 2: Generating XML from a Data Store Step 3: Converting XML into HTML
Texas A&M - ENGL - 104
Writing Project #4: Spaces and Community in Gish Jens Typical AmericanYour AssignmentHow lucky they were! How many people came to this country and bought a house just like that? [] Enormous as the moving van seemed, the new house was more enormous
Texas A&M - ENGL - 104
Writing Project #4: Analyzing Argument in Gish Jen's Typical AmericanYour Assignment Your assignment is to select a topic related to Gish Jen's Typical American (for example, the American Dream, education, consumerism, civil rights, resistance, immi
Texas A&M - ENGL - 104
GRADE DESCRIPTIONS-WRITING PROJECT #1: ANALYZING ARGUMENTSA PAPER: Perhaps the principal characteristic of the A paper is its rich content: rhetorical strategies of the primary article are well evaluated, specific passages are quoted for close analy
Texas A&M - ENGL - 104
Writing Project #1: Analyzing ArgumentStudents Self-Evaluation and Statement of Academic Integrity Directions: Complete this self-evaluation, sign the Statement of Academic Integrity on the back, and turn it in this form with Writing Project #1. Nam
Texas A&M - ENGL - 104
Writing Project #1: Analyzing ArgumentsAssignment Your assignment is to write a coherent, grammatically correct rhetorical analysis (700-800 words) of a persuasive aim article published in an academic journal (read and refereed by scholars). To com