B
B
BadCats2016-08-25 12:17:00
C++ / C#
BadCats, 2016-08-25 12:17:00

Creating a lock object?

hello everyone, here is an example:

class Program
    {
        static object locker = new object();

        static void WriteSecond()
        {
            for (int i = 0; i < 20; i++)
            {
                lock (locker)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine(new string(' ', 10) + "Secondary");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Thread.Sleep(100);
                }
            }
        }

        static void Main()
        {
            Console.SetWindowSize(80, 45);

            ThreadStart writeSecond = new ThreadStart(WriteSecond);
            Thread thread = new Thread(writeSecond);
            thread.Start();
          
            for (int i = 0; i < 20; i++)
            {
                lock (locker)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Primary");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Thread.Sleep(100);
                }
            }

            // Delay.
            Console.ReadKey();
        }
    }

as you can see, two lock critical sections are created, and they use the same lock object in two different methods - one critical section in the WriteSecond method, and the second in the Mian() method, but both of these sections are still within the same class - the Program class.
Perhaps exactly the same "sharing" of the lock object between two critical sections, if these sections are located in different classes?
If this is possible, then I will ask you to give an example of a code with an explanation for it, and if not, why not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ananiev, 2016-08-25
@SaNNy32

If the same object is locked in different classes, then yes, such a division is possible.
In a comment to the question , Michael already indicated how this can be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question