21.8 Locks

The problem illustrated in the previous section raises a principle question: How can we gain the effect of atomic state change? Oz provides locks in order to solve this problems. A lock allows you to block the access of the state of an object until some sequence of operations is executed. For instance, you can repair the program of the above example as follows:

<consistent state change>=
declare 
class C 
   prop locking
   attr 
      x:0
      y:0
   meth change 
      lock 
         x<-@y+1 {Time.delay 500}
         y<-@y+1
      end 
   end 
   meth test 
      lock 
         try 
            if @x==@then {Show ok}
            else {Show 'oh weia'}
            raise done end 
            end 
            thread {self test} end 
            {self change}
            {self test}
         catch _ then {Show stop}  
         end 
      end 
   end 
end 
 
O={New C test}

It should be noted carefully that the lock in the method test is also necessary. Otherwise the test for @x==@y might still return false. The problem is that unlocked methods can still access the state of a locked object. Only locked methods are prohibited to access the state of a locked object.

It might also be worth noting that the method test creates recursively locks inside of locks. Note that nested locks have the same effect as simple locks, i.e. for all statements E it holds that:

lock lock E end end    <==>    lock E end 

In other words, Oz provides for so called thread-reentrant locks (similar to Java).


Denys Duchier, Claire Gardent and Joachim Niehren
Version 1.3.99 (20050412)