0

I wanted to understand dangers of lock(this) with some code example. With the code, if everything works well I expect to see 1000 at the end of program. And that's what I get every time I run it even though I am using lock(this). Why lock(this) works well here?

class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            for (int x = 0; x < 100; x++)
            {
                Thread[] threads = new Thread[10];
                for (int i = 0; i < 10; i++)
                {
                    threads[i] = new Thread(t.ProtectedMethod);
                    threads[i].Start();
                }

                for (int i = 0; i < 10; i++)
                    threads[i].Join();

                Console.WriteLine("Done with {0}", t.i);
            }

        }
    }

    class Test
    {
        public int i = 0;

        public void ProtectedMethod()
        {
            lock (this)
            {
                i++;
            }
        }
    }
whoami
  • 1,689
  • 3
  • 22
  • 45
  • What are the dangers you had in mind? – ryanyuyu Jan 30 '15 at 23:03
  • @tia I had seen that question also but it seem different. Based on that answer, I should have gotten different results than what I am currently getting in code example above. – whoami Jan 30 '15 at 23:11

2 Answers2

0

The lock on this prevents multiple threads to enter the lock code block for the object at the same time. While one thread is in the code block, the other threads are waiting until the current lock on 'this' object is released.

Sievajet
  • 3,443
  • 2
  • 18
  • 22
  • How this will be different if in the Test class I have a local private object and use that for lock in place of lock this? – whoami Jan 30 '15 at 23:10
  • Locking on this is bad practice because you dont know if anyone locks the same object somewhere else – Sievajet Jan 30 '15 at 23:12
  • Making a private object is unique for that particular code block and cannot be affected by code outside your class – Sievajet Jan 30 '15 at 23:13
  • Can you add any example with lock(this) will not produce desired results? – whoami Jan 30 '15 at 23:13
0

It runs okay because example is too simple. It's equivalent to the case when you lock on some private variable. I say that it will even run fine if you wrap for loop with lock (t) since lock supports recursion.

But imagine if other thread had locked on your variable and entered some infinite loop? Just after you created variable? A deadlock would occur.

Now let's imagine you provide your code with lock (this) as 3rd party dll. You never know how smart will be the consumer of your library...

Alex K.
  • 784
  • 5
  • 12