From: Tony Johansson on
Good Expained Arne!!

//Tony


"Arne Vajh�j" <arne(a)vajhoej.dk> skrev i meddelandet
news:4be8b3a6$0$276$14726298(a)news.sunsite.dk...
> On 10-05-2010 09:14, Tony Johansson wrote:
>> At the bottom I have a class named Counter and in a method called
>> UpdateCount I use this statement
>> lock(this) to synchronize so that only one thread can access this section
>> of
>> code. In class Test is main located also listed at the end.
>>
>> I made a test to access method Foo in this class Counter using the same
>> object as I do when calling method UpdateCount
>> and it worked. First I was a litle uncertain if this statement lock(this)
>> will lock the object this in any way but it doesn't.
>>
>> So accoding to my test this argument that is passed to lock here this
>> which
>> is the currect Counter object is not locking
>> this Counter object in any way.
>>
>> So what purpose has this argument that is passed to lock actually if it
>> doesn't lock the current object which I first thought..?
>
> lock is a cooperative locking mechanism not an enforcing locking
> mechanism.
>
> Think of:
>
> lock(obj) {
> ...
> }
>
> as:
>
> obj.WaitUntilLockFlagNotSetAndThenSetLockFlag();
> ...
> obj.UnsetLockFlag();
>
> It does not put obj in a state where other code can
> not use it.
>
> It only synchronizes with other code that also uses
> the lock flag of the object.
>
> This is possible:
>
> thread #1 thread #2
>
> lock(obj) {
> obj.foo(); obj.bar();
> }
>
> This is not possible:
>
> thread #1 thread #2
>
> lock(obj) { lock(obj) {
> obj.foo(); obj.bar();
> } }
>
> so it will become either:
>
> thread #1 thread #2
>
> lock(obj) {
> obj.foo();
> }
> lock(obj) {
> obj.foo();
> }
>
> or:
>
> thread #1 thread #2
>
> lock(obj) {
> obj.foo();
> }
> lock(obj) {
> obj.foo();
> }
>
> Arne