[英]variable safety in unity thread
据我所知,如果未锁定,线程中的变量应该是不安全的。 但是我在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;
}
}
, and every times I try it that is 10000. But it should be a number which is less than 10000 because of not thread safety, shouldn't it? 并且我尝试使用 ,每次尝试都为10000。但是由于不是线程安全性,它应该是小于10000的数字,不是吗? 谁能告诉我为什么?
这是代码的最小,完整和可验证的示例 :
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 < 50000; i++)
然后一次运行的结果是89922
。 每次都会改变,但有时我仍然会得到100000
。
该线程需要一些时间来计划启动。 主线程可能会在另一个线程开始之前完成增量。 尝试使用较大的值,例如50000000。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.