locked
Lock keyword not working properly RRS feed

  • Question

  • User-307604573 posted

    I have written a code which is as below:I am not able to understand the out as I get output different.

    The code:

        class Class6
        {
            static StringBuilder text = new StringBuilder();
            public static void Main()
            {
            Thread firstThread = new Thread(new ThreadStart(Fun1));
    Thread secondThread = new Thread(new ThreadStart(Fun2));
    firstThread.Start();
    secondThread.Start();
    firstThread.Join();
    secondThread.Join();
    Console.WriteLine("Text is:\r\n{0}", text.ToString());
    }
        
    public static void Fun1()
    {
    lock(text)
    {
    for(int i=1; i<=200; i++)
    {
    Thread.Sleep(10);
    text.Append("First Threadd \n "+i.ToString() + " ");

    }
    }
    }
    public static void Fun2()
    {
    lock(text)
    {
        
    for(int i=21; i<=400; i++)
    {
    Thread.Sleep(2);
        
    text.Append("second thread \n"+i.ToString() + " ");
    }
    }
    }
    }
        }
    here when I have iteration which is small numbers then it works fine with LOCK.
    But as loop is for larger value which is in the code,then output varies at times it shows only First thread or only second thread wherein again
    numbers displayed are not as per given in the loop.It skips many numbers and it is very unpredictable output.Can anyone explain correctly.

    why it is the case..Should I Use Monitor class instead....

    Thanks in advance

    Friday, November 28, 2014 7:17 AM

Answers

  • User-760709272 posted

    The buffer in your console is probably just not set to store all the lines you need.  Write it to the debug output and look at that instead

    Thread firstThread = new Thread(new ThreadStart(Fun1));
    Thread secondThread = new Thread(new ThreadStart(Fun2));
    firstThread.Start();
    secondThread.Start();
    firstThread.Join();
    secondThread.Join();
    Console.WriteLine("Text is:\r\n{0}", text.ToString());
    System.Diagnostics.Debug.WriteLine(text.ToString());
    Console.ReadKey();

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 28, 2014 7:51 AM