c# - parallel.foreach 有效,但为什么呢?

标签 c# .net thread-safety race-condition parallel.foreach

谁能解释一下,为什么这个程序会返回正确的 sqrt_min 值?

int n = 1000000;

double[] myArr = new double[n];
for(int i = n-1 ; i>= 0; i--){ myArr[i] = (double)i;}

// sqrt_min contains minimal sqrt-value
double sqrt_min = double.MaxValue;

Parallel.ForEach(myArr, num =>
{
double sqrt = Math.Sqrt(num); // some time consuming calculation that should be parallized
if(sqrt < sqrt_min){ sqrt_min = sqrt;}
});
Console.WriteLine("minimum: "+sqrt_min);

最佳答案

这完全靠运气。有时当您运行它时,您幸运对 double 的非原子读取和写入不会导致“撕裂”值。有时你很幸运非原子测试和设置恰好在比赛发生时设置了正确的值。不保证此程序会产生任何特定结果。

关于c# - parallel.foreach 有效,但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9166201/

相关文章:

c# - 使用大括号格式化 C# 中的输出

带有 native Windows 渲染器的 .NET MenuStrip?

multithreading - 多线程 X11 应用程序和 OpenGL

php - PHP 是线程安全的吗?

c# - 使用 threadstatic 静态字段模拟函数静态变量?

c# - Entity Framework 核心 1.0 PostgreSQL API

c# - 报告表格未在 VS 2013 中显示

c# - 在 asp.net mvc 中使用 Razor 的 Css View 模型

c# - 安卓手机浏览器检测

.net - 在 Azure DevOps 持续部署期间无法获取资源类型 'Microsoft.Web/Sites' 和资源名称 'AppService' 的资源 ID