为什么下面的C#多线程代码不输出为零,虽然它在调试程序? [英] Why the following C# multi-threaded code does not output zero though it does in debugger?

查看:163
本文介绍了为什么下面的C#多线程代码不输出为零,虽然它在调试程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 类节目
{
私有静态挥发int值;

公共静态无效增量()
{
的for(int i = 0; I< 100000;我++)
{
值++;
}
}

公共静态无效递减()
{
为(INT J = 0; J< 100000; J ++)
{
value--;
}
}

公共静态无效ThreadTest()
{
值= 0;

变种incrementThread =新主题(增量);

变种decrementThread =新主题(递减);

incrementThread.Start();

decrementThread.Start();

incrementThread.Join();

decrementThread.Join();

Console.WriteLine(,值的值{0}值);
}

静态无效的主要(字串[] args)
{
ThreadTest();
}
}


解决方案

由于它不应该... ... + +和 - 不是原子操作(不像Interlocked.XXXX opreations - Interlocked.Increment)。



如果您记下每一步的++和 - 和怎么看都可以通过不同的线程混合使用,你会明白为什么:



增加

  1:负载值温度
2:增加温度,1
3:存放温度为价值

递减

  4:负载值TEMP2 
5:substruct TEMP2,1
6:店内TEMP2价值

所以,如果为了就是你得到1,2,3,4,5,6值= 0;但如果订单是1,2,4,5,6,3你得到的价值= 1。


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();
    }
}

解决方案

Because it is not supposed to... ++ and -- are not atomic operations (unlike Interlocked.XXXX opreations - Interlocked.Increment).

If you write down each step of ++ and -- and see how both can be intermixed by different threads you'll see why:

increment

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

decrement

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

So if order is 1,2,3,4,5,6 you get value = 0; but if order is 1,2,4,5,6,3 you get value = 1.

这篇关于为什么下面的C#多线程代码不输出为零,虽然它在调试程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆