Locking keyword more explained

Hi all,

I have been fiddling with threads some more, and ran into issues using the “locking” keyword. The issue is: I get null-errors (the object is null, which is quite strange as they are basic types).

Example code:

var myWaitSignal : boolean := false;

ObjectThatGetsFilledByOtherThread.Setsignal := method begin locking WaitSignal do WaitSignal  := true; end;
var WaitCOunt : Integer := 40;
var WaitSignal : boolean := false;
/// ...
/// start other thread that will do something with ObjectThatGetsFilledByOtherThread
/// ...
  repeat
    dec(WaitCount);
    locking Waitsignal do myWaitSignal := WaitSignal;    // make a local copy to prevent the lock to last during the sleep   
    if myWaitSignal  = false then Thread.Sleep(250);
  until (WaitCount <= 0) or (myWaitSignal );

On both places where the locked keyword is used, the null-exception is raised. Maybe locking is not allowed on basic types (not in wiki)? Or is there some other restriction that I’m not aware of?

BTW: I changed the code so the ObjectThatGetsFilledByOtherThread has a locked boolean property, that makes the code much more simple and it just works.

Hugo,
if I remember correctly, the locking in .NET should be made only against objects, and a Boolean is not an object.
Perhaps the compiler should generate an error in this case.
Patrick

Indeed it probably shouldn’t let you do that on basic objects. What’s happenning is that it takes an Object and gets boxed, and later gets boxed again, you shouldn’t “lock” basic objects (best use a dedicated Object for this, var lLock := new Object; locking lLock do …).

Logged as bugs://55190.

Strangely enough locking a boolean property with the locked keyword does work, but that probably uses completely other code.

Your solution probably should reflect if it is necessary to synchronize a basic object like a boolean. Can there be problems when a boolean is updated while another thread is reading it? Or is that such an atomic action that it never will give problems? If it can, it would be more user-friendly to support locking basic types, just to keep simple code. If locking a boolean var is senseless, then giving a compiler error is the best solution.

Locking changing valuetypes makes no sense. You always lock the value, not the variable itself, and that’s what you’re trying to change.