【问题标题】:variable safety in unity thread统一线程中的可变安全性
【发布时间】:2017-07-11 21:52:31
【问题描述】:

据我所知,线程中的变量如果没有锁定应该是不安全的。但我在 Unity 上尝试过,发现它有所不同。 我试试下面的代码:

    void Awake () {
        Thread thread = new Thread(new ThreadStart (demo));
        thread.Start ();
        for (int i = 0; i < 5000; i++) {
            count = count + 1;
        }
    }

    void demo() {
        for (int i = 0; i < 5000; i++) {
            count = count + 1;
        }
    }

我尝试Debug.Log(count),每次尝试都是10000。但它应该是一个小于10000的数字,因为不是线程安全,不应该'是吗?那么谁能告诉我为什么?

【问题讨论】:

  • 您能否发一个minimal reproducible example 以便我们可以复制粘贴并运行您的代码?
  • 你能告诉我们你调用唤醒方法的代码吗
  • @OusmaneDiaw - 我们需要完整的代码,而不仅仅是对 .Awake() 的调用。我们需要一个minimal reproducible example

标签: c# multithreading unity3d thread-safety


【解决方案1】:

线程需要一些时间来安排启动。主线程可能会在另一个线程开始之前完成增量。尝试使用较大的值,例如 50000000。

【讨论】:

    【解决方案2】:

    这是您的代码的Minimal, Complete, and Verifiable example

    void Main()
    {
        Awake();
        Console.WriteLine(count);
    }
    
    private int count = 0;
    
    public void Awake()
    {
        Thread thread = new Thread(new ThreadStart(demo));
        thread.Start();
        for (int i = 0; i < 5000; i++)
        {
            count = count + 1;
        }
        thread.Join();
    }
    
    public void demo()
    {
        for (int i = 0; i < 5000; i++)
        {
            count = count + 1;
        }
    }
    

    如果你运行它,你会得到10000。这是因为当线程启动时,.Awake() 方法已经完成了它的循环,因此不会发生冲突。

    尝试将循环更改为for (int i = 0; i &lt; 50000; i++),然后我运行一次得到的结果是89922。它每次都会改变,但有时我仍然会收到100000

    【讨论】:

    • 感谢您的回复,这对我很有帮助。
    猜你喜欢
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2013-07-06
    • 2023-01-04
    • 2013-07-06
    • 1970-01-01
    相关资源
    最近更新 更多