gpt4 book ai didi

c# - 为什么以下 C# 多线程代码在调试器中不输出零?

转载 作者:太空狗 更新时间:2023-10-29 18:12:37 26 4
gpt4 key购买 nike

class Program
{
private static volatile int value;

public static void Increment()
{
for (int i =0; i <100000; i++)
{
value++;
}
}

public static void Decrement()
{
for (int j =0 ; j < 100000; j++)
{
value--;
}
}

public static void ThreadTest()
{
value = 0;

var incrementThread = new Thread(Increment);

var decrementThread = new Thread(Decrement);

incrementThread.Start();

decrementThread.Start();

incrementThread.Join();

decrementThread.Join();

Console.WriteLine("Value of value {0}", value);
}

static void Main(string[] args)
{
ThreadTest();
}
}

最佳答案

因为它不应该...++ 和 -- 不是原子操作(不同于 Interlocked.XXXX 操作 - Interlocked.Increment)。

如果你写下++ 和 -- 的每一步,看看不同线程如何将两者混合,你就会明白为什么:

增量

1: load value to temp
2: add temp, 1
3: store temp to value

递减

4: load value to temp2
5: substruct temp2, 1
6: store temp2 to value

因此,如果顺序为 1,2,3,4,5,6,则值 = 0;但是如果顺序是 1,2,4,5,6,3 你得到值 = 1。

关于c# - 为什么以下 C# 多线程代码在调试器中不输出零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com