V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
FreeWong
V2EX  ›  编程

===Gemini、Copilot 都说有线程安全问题我说没有===

  •  
  •   FreeWong · 21 天前 · 414 次点击

    以下 c#代码,不懂 c# 我也加了注释 我说以下代码并没有线程安全问题,但是我问了 Gemini 、Copilot 他们都说有问题

    namespace helloworld
    {
        internal class Program
        {
            static void Main()
            {
                int foo =0;
                //新建一个线程
                var t = new Thread(() => 
                {
                    foo++;
                } );
                t.Start(); //启动上面这个线程
                t.Join();  //主线程阻塞直到 t 线程完成
                Console.WriteLine(foo);
            }
        }
    
    }
    
    
    abelai
        1
    abelai  
       21 天前
    建议直接问 foo++ 是否会有线程安全问题
    FreeWong
        2
    FreeWong  
    OP
       21 天前
    @abelai foo++ 不是线程安全的。
    xuanbg
        3
    xuanbg  
       11 小时 41 分钟前
    在另一个线程操作主线程的变量还能线程安全?也就是你这段代码特殊罢了,但凡后面再加一行 foo = 1 ,你都不知道结果是个啥。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1029 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 18ms · UTC 19:53 · PVG 03:53 · LAX 12:53 · JFK 15:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.