Compare-and-swap for Mozart?

Maximilian Wilson wilson.max at gmail.com
Tue Dec 27 02:38:36 CET 2005


I'm reading through Keir Fraser's dissertation on Pratical
lock-freedom (http://www.cl.cam.ac.uk/TechReports/UCAM-CL-TR-579.pdf)
and have the urge to try some of his algorithms out in Oz. However, he
relies on a primitive compare-and-swap which doesn't seem to exist in
Oz.

Pseudocode:
CompareAndSwap( Cell OldValue NewValue )
  ATOMIC:
  if @Cell == OldValue
     Cell := NewValue
     return OldValue
  else
     return @Cell

I've tried to emulate this with Cell.exchange but the closest I can
come is this:

% Attempt to emulate atomic compare-and-swap
declare
fun {CAS Cell Old New}
   New_ Old_ in
   try
      Old_ = @Cell
      {Exchange Cell Old New_} % fail if Cell does not have expected value...
      New_ = New
      Old_
   catch failure(...) then
      New_ = Old_
      Old_
   end
end

Alas, this function doesn't act atomic, since there's a race condition
between New_=New and the unification with Old in Exchange.

% The following code will usually throw a TELL error
declare
Count={NewCell 0}
proc{Inc}
   OldVal = @Count
   NewVal = OldVal + 1
   WriteVal = {CAS Count OldVal NewVal} in
   if OldVal \= WriteVal then {Inc}
   end
end
Threads = 1000
Synch = {NewArray 1 Threads _}
for I in 1..Threads do
   thread
      for J in 1..100 do
	 {Inc}
      end
      Synch.I = unit
   end
end
for I in 1..10 do
   {Wait Synch.I}
end
{Show @Count}

Am I missing a trick, or do I have to implement the new primitive in
C++ functor or something?

Thanks muchly,
Max

--
Be pretty if you are,
Be witty if you can,
But be cheerful if it kills you.




More information about the mozart-hackers mailing list