13.07.2015 Views

An Operating Systems Vade Mecum

An Operating Systems Vade Mecum

An Operating Systems Vade Mecum

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Mechanisms 2711 activity E:2 Down(B);3 Down(D);4 perform E’s work;5 Up(E); { once for F, once for H }6 Up(E);One of the exercises at the end of the chapter explores another way to use semaphores tosolve the same problem.2.7 Critical regionsSemaphores provide the power we need, but they are easy to misuse. The following sectionsdeal with ways to embed semaphores in programming-language constructs that tryto minimize three problems:(1) Failure to protect shared variables(2) Failure to invoke semaphore operations in the right order and at the right time(3) Deadlock and starvationWe begin by a programming-language construct called the critical region. It is meant tobe part of any language that explicitly allows several activities to share variables. Variablesthat are shared must be so declared; they are the only global variables that activitiesare allowed to access. Access to shared variables is restricted to code that lies within theregion statement, as shown here:1 var2 v : shared integer;34 . . .56 region v do7 v := 15;8 write(v);9 end;We no longer use explicit calls to procedures BeginRegion and EndRegion; the compilerinserts those calls (most likely, calls to semaphores) for us.There is a danger of deadlock because activity A might nest (that is, embed)region v inside region w, whereas activity B might nest them in the other order.Sometimes the compiler can check the order of nesting and disallow conflicting orders.However, if a region includes a call to a procedure that then enters another region, a nestingsituation arises that the compiler cannot be expected to detect. Still, an impermissibleorder can be discovered when the program runs. <strong>An</strong>other way to skirt the problem is toavoid nesting. If a single region needs to use several shared variables, they may be listedin the region statement. In this case, the compiler may choose any order it wishes toacquire the semaphores. A consistent order is equivalent to a hierarchical allocation rule.If several activities are waiting for the same shared variable, we can protect againststarvation by making sure the underlying semaphores keep all waiting activities in afirst-in, first-out queue.Regions protect the programmer against two mistakes that are common with semaphores.First, there is no way to access a shared variable from outside a region.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!