Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the lock in this code is not working ?

Tags:

c#

I wrote simple code ( attached ) and i don't understand why the lock on some block is not locking the scope.

The code :

    object locker = new object();
    private void foo(int i)
    {
        Console.WriteLine( string.Format( "i is {0}", i ) );
        lock( locker )
        {
            while( true )
            {
                Console.WriteLine( string.Format( "i in while loop is {0}", i ) ) ;
                foo( ++i );
            }
        }
    }

I expect that the calling for the foo method in the while loop will be waiting until the locker will be release ( locker scope ) - but all the calls of the foo with arg of ++i can enter to the locker block.

like image 408
Yanshof Avatar asked Apr 11 '12 03:04

Yanshof


3 Answers

The lock used here is reentrant. It will prevent another thread from entering the monitor, but the thread holding the lock will not be blocked.

like image 112
Gabe Avatar answered Nov 07 '22 05:11

Gabe


Lock doesn't apply if you are on the same thread. See http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

like image 42
StuartLC Avatar answered Nov 07 '22 06:11

StuartLC


The lock keyword is just syntactic sugar around the Monitor.Enter and Monitor.Exit methods. As seen in the documentation for Monitor:

It is legal for the same thread to invoke Enter more than once without it blocking;

Calling lock(object) from the same thread more than once has no effect other than to increase the lock count.

like image 30
Michael Edenfield Avatar answered Nov 07 '22 05:11

Michael Edenfield