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 2672.5 LocksThe switch solutions we have seen are store-synchronous; they assume that individualreferences to main store are atomic. Many computers offer an explicit store-synchronousinstruction that makes mutual exclusion far easier and clearer. This instruction atomicallyreads a variable and sets it to a new value. The most common design is to set thenew value to 1 no matter what the old value. In this case, the instruction is called Testand Set. It has the following behavior:1 atomic function Test<strong>An</strong>dSet(var Lock : Boolean) : Boolean;2 begin3 Test<strong>An</strong>dSet := Lock;4 Lock := true;5 end Test<strong>An</strong>dSet;One of the exercises explores a different atomic action that increments the old value.Given Test and Set, we can build a simple mutual-exclusion mechanism called alock:1 type Lock = Boolean;23 procedure BeginRegion(var L : Lock);4 begin5 while Test<strong>An</strong>dSet(L) do6 null;7 end;8 end BeginRegion;910 procedure EndRegion(var L : Lock);11 begin12 L := false;13 end;Each region that an activity might enter uses a number of shared variables that must beprotected. Each such group of shared variables is assigned a lock variable. Before enteringa region, an activity is expected to call BeginRegion on the appropriate lock. Ifseveral locks are needed, they should be acquired in a standard hierarchical order toprevent deadlock. It makes no difference in what order they are released at the end of theregion.This solution works because the Test<strong>An</strong>dSet instruction (line 5) will return true aslong as some other activity is in a conflicting region. When it returns false, it simultaneouslysets the lock to true so that any other activity trying to acquire the lock will fail. Ifseveral activities are trying to get the same lock and the activity with the lock releases it(line 12), only one of the contenders will get it because Test<strong>An</strong>dSet is atomic. (Whichone of the contenders gets it is arbitrary and depends on hardware arbitration.)The lock method has the following properties:It works for any number of activities on any number of processors sharing mainstore.It is simple and easy to verify.

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

Saved successfully!

Ooh no, something went wrong!