Multithreading in C#
<p>I am trying to run the following program from the book. </p>

<p>The author claims that the resultant output 
" should be "</p>

<p>1000</p>

<p>2000</p>

<p>....</p>

<p>10000</p>

<p>if you run the program on normal processor but on multiprocessor computer it could be</p>

<p>999</p>

<p>1998</p>

<p>...</p>

<p>9998 </p>

<p>when using normal increment method (number+=1) but using the intelocked increment as shown in the program solves the problem(i.e. you get first output)</p>

<p>Now I have got 3 questions.
First why cant i use normal increment in the inner loop [i++ instead of Interlocked.Increment(ref i)]. Why has author choosed the other method? </p>

<p>Secondly what purpose does Thread.Sleep(1000) has in the context. When I comment out this line, I get second output even if I am using Interlocked method to increment number. </p>

<p>Thirdly I get correct output even by using normal increment method [number += 1] if I dont comment the Thread.Sleep(1000) line and second output if I do so.</p>

<p>Now I am running the program on Intel(R) Core(TM) i7 Q820 cpu if it makes any difference</p>

<pre><code>static void Main(string[] args)
{
    MyNum n = new MyNum();

    for (int a = 0; a &lt; 10; a++)
    {
        for (int i = 1; i &lt;= 1000; Interlocked.Increment(ref i))
        {
            Thread t = new Thread(new ThreadStart(n.AddOne));
            t.Start();
         }            
        Thread.Sleep(1000);
        Console.WriteLine(n.number);
    }
}

class MyNum
{
    public int number = 0;
    public void AddOne() 
    {
        Interlocked.Increment(ref number);
    }
}
</code></pre>
