我试图从这本书中操作以下方案。
The author claims that the resultant output " should be "
页: 1
2000年
............
页: 10
如果管理正常处理器方案,但使用多处理器计算机,可以操作。
999
1998年
......
9998
采用正常的加固方法(编号+=1)但采用方案所示的内锁加法解决了这一问题(即,你先获得产出)。
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?
Secondly what purpose does Thread.Sleep(页: 1) has in the context. When I comment out this line, I get second output even if I am using Interlocked method to increment number.
Thirdly I get correct output even by using normal increment method [number += 1] if I dont comment the Thread.Sleep(页: 1) line and second output if I do so.
现在,我正在执行英特尔(R)核心方案,如果该方案有任何改变的话,即7 Q820 cpu。
static void Main(string[] args)
{
MyNum n = new MyNum();
for (int a = 0; a < 10; a++)
{
for (int i = 1; i <= 页: 1; Interlocked.Increment(ref i))
{
Thread t = new Thread(new ThreadStart(n.AddOne));
t.Start();
}
Thread.Sleep(页: 1);
Console.WriteLine(n.number);
}
}
class MyNum
{
public int number = 0;
public void AddOne()
{
Interlocked.Increment(ref number);
}
}