V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
FreeWong
V2EX  ›  编程

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

  •  
  •   FreeWong · Mar 4, 2025 · 1395 views
    This topic created in 429 days ago, the information mentioned may be changed or developed.

    以下 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  
       Mar 4, 2025
    建议直接问 foo++ 是否会有线程安全问题
    FreeWong
        2
    FreeWong  
    OP
       Mar 4, 2025
    @abelai foo++ 不是线程安全的。
    xuanbg
        3
    xuanbg  
       Mar 25, 2025
    在另一个线程操作主线程的变量还能线程安全?也就是你这段代码特殊罢了,但凡后面再加一行 foo = 1 ,你都不知道结果是个啥。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5623 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 123ms · UTC 07:22 · PVG 15:22 · LAX 00:22 · JFK 03:22
    ♥ Do have faith in what you're doing.