Skip to content

Instantly share code, notes, and snippets.

@huanlin
Last active October 11, 2022 05:02
Show Gist options
  • Save huanlin/d526c23ab01139c5a66cc56013cc86c5 to your computer and use it in GitHub Desktop.
Save huanlin/d526c23ab01139c5a66cc56013cc86c5 to your computer and use it in GitHub Desktop.
觀察 Random API 的執行緒安全問題
using System;
using System.Linq;
using System.Threading.Tasks;
public class Program
{
public static void Main()
{
var rng = new Random();
Parallel.For(0, 16, _ =>
{
var numbers = new int[10000];
for (var i = 0; i < numbers.Length; i++)
{
numbers[i] = rng.Next();
}
int zeroCount = numbers.Count(y => y == 0);
Console.WriteLine("隨機函數產生了 {0} 個零。", zeroCount);
});
// 提示:隨機函數不應該產生很多 0。
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment