A
A
Aleviy2021-12-03 00:46:11
C++ / C#
Aleviy, 2021-12-03 00:46:11

Why doesn't the second thread start when using the TryEnter() construct?

using System;
using System.Threading;


class Demo 
{
    static int Count;
    static object Locker = new object();
    static void Main() 
    {
        Thread ob = new Thread(Run);
        ob.Name = "first ";
        Thread ob1 = new Thread(Run);
        ob1.Name = "second ";
        ob.Start();
        ob1.Start();
        ob.Join();
        ob1.Join();
    }

    public static void Run() 
    {
        if (Monitor.TryEnter(Locker)) 
        {
            do
            {
                Thread.Sleep(100);
                Console.WriteLine(Thread.CurrentThread.Name + " вошел " + Count);
                Count++;

            } while (Count < 10);
            Console.WriteLine(Thread.CurrentThread.Name + " закончил свою работу");
            Count = 0;
            Monitor.Exit(Locker);
        }
        else 
        {
            Console.WriteLine("Не вошел " + Thread.CurrentThread.Name);
        }
    }
        
}


Actually, one of the threads is blocked by the object object, but when this thread finishes its work, the whole process stops. Why doesn't the second thread enter the critical region?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2021-12-03
@Nipheris

Well, apparently because the second thread failed to capture the lock, it went to the else branch and, after displaying the message, completed its work, because there are no more instructions in the body of the Run function.
It's strange that you ask this if you wrote this code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question