c# - 线程竞速,为什么线程这么工作?

标签 c# multithreading static thread-safety

交换两行代码(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/

相关文章:

c# - 您如何在 C# 中模拟文件系统以进行单元测试?

c# - 如何在资源/常量/字符串/其他中嵌入 AssemblyFileVersion?

c# - 从 Internet 下载 HTML 后,字符串中的字符发生了变化

c - 如何在 C 静态函数上设置 VxWorks 断点?

java - 将实例变量分配给静态变量

c++ - 具有静态成员变量的奇怪 C++ 模板行为

c# - 比较位图列表中图像的最佳方法是什么

Java - 两个线程不同步

python - 让 Python 等待函数完成后再继续执行程序

iphone - 为什么我更愿意为每个新线程或 NSOperation 创建一个 NSManagedObjectContext 而不是在主线程上调用核心数据?