Last active
October 11, 2022 05:02
-
-
Save huanlin/d526c23ab01139c5a66cc56013cc86c5 to your computer and use it in GitHub Desktop.
觀察 Random API 的執行緒安全問題
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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