Simple C# concurrency / multithreading
I'm probably missing something basic here, but still would appreciate your
kind help in understanding this. So I have the following simple
multithreaded program I wrote:
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //            List<int> outcome = new List<int>();
            Test t = new Test();
                Thread thread1 = new Thread(new ThreadStart(t.call1));
                Thread thread2 = new Thread(new ThreadStart(t.call2));
                thread1.Start();
                thread2.Start();
                Thread.Sleep(3000); //Give enough time for threads to end
                Console.Write("{0},", t.mSum);
                t.mSum = 0;
        }
    }
    class Test
    {
        public int mSum = 0;
        public void call1()
        {
            //lock (this)
            //{
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("Hello Thread 1, mSum value: {0}", mSum);
                mSum = mSum + 1;
                Console.WriteLine("Goodbye Thread 1, mSum value: {0}", mSum);
            }
            //}
            //  Console.WriteLine(mSum);
        }
        public void call2()
        {
            for (int i = 0; i < 100 ; i++)
            {
                Console.WriteLine("Hello Thread 2, mSum value: {0}",mSum);
                mSum = mSum + 1;
                Console.WriteLine("Goodbye Thread 2, mSum value: {0}",mSum);
            }
        }
    }
}
So I would expect this output to be nondetermenistic because context
switching can occur anytime right? But when I run the program, I get the
following output (only a part of the output, malformed due to my poor
stackoverflow.com question posting skills):
Hello Thread 1, mSum value: 62 Goodbye Thread 1, mSum value: 63
Hello Thread 1, mSum value: 63 Goodbye Thread 1, mSum value: 64
Hello Thread 2, mSum value: 59 Goodbye Thread 2, mSum value: 65
Hello Thread 2, mSum value: 65 Goodbye Thread 2, mSum value: 66
So, assuming I wrote this right, and mSum is indeed shared between the
threads (looks like it...) - how can I explain line no. 3? Thread 2 reads
59, adds 1 and then we get 65!
Did I discover a new kind of math? :)
Thanks in advance.
 
No comments:
Post a Comment