Diego Pacheco
Diego Pacheco

Reputation: 1045

Synchronising threads: is there a conflict here?

class Class1
    {
        private static object consoleGate = new Object();

        private static void Trace(string msg)
        {
            lock (consoleGate)
            {
                Console.WriteLine("[{0,3}/{1}]-{2}:{3}", Thread.CurrentThread.ManagedThreadId,
                    Thread.CurrentThread.IsThreadPoolThread ? "pool" : "fore",
                    DateTime.Now.ToString("HH:mm:ss.ffff"), msg);
            }
        }
        private static void ProcessWorkItems()
        {
                    lock (consoleGate)
                    {
                        for (int i = 0; i < 5; i++)
                        {
                            Trace("Processing " + i);
                            Thread.Sleep(250);
                        }
                    }
            Console.WriteLine("Terminado.");

        }
        static void Main()
        {
            ProcessWorkItems(); Console.ReadLine();
        }
    }

output:

Processing 0
Processing 1
Processing 2
Processing 3
Processing 4
Terminated

Why is this code works? ProcessWorkItems static method locks ConsoleGate object and Trace did the same. I thought the object could only be locked once. ¿Some explanations?

Upvotes: 0

Views: 118

Answers (2)

Andrei G
Andrei G

Reputation: 1590

All the code you have displayed here is running on the same thread. That is why it is running just like it would if you hadn't used "lock"

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160912

locks in C# are re-entrant - a single thread can acquire the same lock multiple times without blocking. Sine you only have one thread here there is no problem - locks are for synchronizing access to resources across multiple threads.

From the MSDN documentation on lock:

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

For more information on re-entrant-locking see this SO thread: "What is the Re-entrant lock and concept in general?"

Upvotes: 4

Related Questions