gpt4 book ai didi

c# - 即使在线程中使用 Join() 后得到不同的答案 - C#

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:26 24 4
gpt4 key购买 nike

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Threading;
namespace JUSTFORPRACTICE
{
class Program
{
static int total = 0;
public static void Main()
{
Thread t1 = new Thread(fun);
t1.Start();
Thread t2 = new Thread(fun);
t2.Start();
Thread t3 = new Thread(fun);
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine(total);
}
public static void fun()
{
for (int i = 1; i <= 10000; i++)
total++;
}
}

}

我读过使用 Join() 可以阻止主线程执行后续语句,直到当前线程运行。但是每次我运行时都会得到不同的输出。 ....为什么?

最佳答案

您同时运行三个线程,所有线程都以不安全的方式改变共享状态:

  • 递增不是原子的,因为它是“读取、本地递增、写入”——如果多个线程读取相同的值,然后每个本地递增,然后写入,你将有效地“丢失”除了一个之外的所有增量。
  • 没有内存屏障来强制每个线程从主内存中读取变量的最新值或立即将结果写回到主内存。每个线程可以执行fun作为“从主内存读取一次到寄存器中;将寄存器递增10001次;将结果写回主内存”...

如果将 total++ 更改为 Interlocked.Increment(ref total) 那么每个增量操作都是原子的,并且保证对新数据起作用,结果是可见的立即发送给所有线程。

问题的寓意:在处理来自多个线程的可变共享数据时要格外小心。

关于c# - 即使在线程中使用 Join() 后得到不同的答案 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31161795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com