交换两行代码(done = true with Console.Write() one)我有两个不同的结果
如果我首先输入 done = true,结果将是: 是的
否则,如果我先放置 Console.WriteLine(),结果将是: 错误 假的
为什么? (仔细看,那个 bool 变量是静态的!)
using System;
using System.Threading;
class Program
{
static bool done;
static void Main(string[] args)
{
new Thread(test).Start();
test();
}
static void test()
{
if (!done)
{
done = true;
Console.WriteLine(done);
}
}
}
最佳答案
我敢打赌,Console.WriteLine
足以让线程保持忙碌,而对 test()
的第二次调用有机会执行。
所以基本上 WriteLine
的调用延迟了 done
的设置足够长的时间,以便第二次调用 test
能够测试 done
发现它仍然设置为 false
。
如果你保持它如图所示,在写入控制台之前使用 done = true;
那么这将几乎立即设置,因此第二次调用测试将发现 done
设置为 true
,因此不会执行 Console.WriteLine
。
希望一切都有意义。
我只是found this其中包含与您的问题非常相似的代码。如果您还没有从这个页面得到您的问题,那么我建议您阅读一下,因为它更详细地解释了造成这种影响的原因。
使用以下关键摘录:
On a single-processor computer, a thread scheduler performs time-slicing — rapidly switching execution between each of the active threads. Under Windows, a time-slice is typically in the tens-of-milliseconds region — much larger than the CPU overhead in actually switching context between one thread and another (which is typically in the few-microseconds region).
所以本质上,对 Console.WriteLine
的调用花费了足够长的时间让处理器决定是时候让主线程再运行一次,然后你的额外线程才被允许继续(最终设置完成
标志)
关于c# - 线程竞速,为什么线程这么工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12002117/