I heard a lot of the corruption that could be made by the multiple threads when they share same data. And understanding why that happen is not so hard, but I wanted some bright example of it, which will be able to quickly show what is going on.

So here is my example:

    public class Counter
    {
        public
int Count = 0;
        public
void UpdateCount()
        {
            for
(int i = 0; i < 10000; i++)
            {
                Count = Count + 1;
            }
        }
    }
    class Program
    {
        static
void Main(string[]
args)
        {
            var
counter = new Counter();
            var
threads = new Thread[500];
            for
(int i = 0; i < threads.Length;
++i)
            {
                threads[i] = new Thread(counter.UpdateCount);
                threads[i].Start();
            }
            foreach
(var thread in threads)
                thread.Join();
            Console.WriteLine(string.Format(
                @”If you are running this code on multiple processors machine you
probably will not get expected ThreadCount*Iterations={0}*{1}={2}, but
less number, which is currently equal to {3}”
,
                    threads.Length, 10000,
threads.Length * 10000, counter.Count));
        }
    }

As you see I’m using 500 threads. Why? First it is because this ensures that lot of them will be allocated on another processor and second is because the UpdateCount runs “Count = Count + 1” that is quite very trivial and requires about 3 atomic operations, so to increase possibility to run them in concurrent threads I increased their count.

Below is the output:

If you are running this code on multiple processors machine you probably will no
t get expected ThreadCount*Iterations=500*10000=5000000, but less number, which
is currently equal to 4994961
Press any key to continue . . .
As you see the actual number of the Count field is less than expected. We lost one each time when next happens at once:
Thread 1: Reads Count (1000)
Thread 2: Reads Count (1000)
Thread 1: Increases Count (1001)
Thread 2: Increases Count (1001)
Thread 1: Writes Count (1001)
Thread 2: Writes Count (1001) – he-he so it wrote back the same number, not 1002
You probably already know how to solve this with lock or Interlocked class or other stuff.
For example just change line Count = Count + 1; with line Interlocked.Increment(ref Count); or lock (this)Count = Count + 1; But I’m getting fun writing this.
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone