I am trying to run the following program from a book.
The author claims that the result "must be"
1000
2000
....
10,000
if you run the program on a regular processor, but on a multiprocessor computer it may be
999
1998
...
9998
using the normal increment method (number + = 1), but using increments intelocked, as shown in the program, solves the problem (i.e. you get the first result)
Now I have 3 questions. First, why am I not using normal growth in the inner loop [i ++ instead of Interlocked.Increment (ref i)]. Why did the author choose another method?
Secondly, what purpose does Thread.Sleep (1000) have in context. When I comment on this line, I get the second output, even if I use the Interlocked method to increase the number.
Thirdly, I get the correct output even when using the usual increment method [number + = 1] if I do not comment on the Thread.Sleep (1000) line and the second output if I do it.
Now I run the program on the Intel (R) Core i7 Q820 processor, if that matters
static void Main(string[] args) { MyNum n = new MyNum(); for (int a = 0; a < 10; a++) { for (int i = 1; i <= 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); } }
source share