Created
December 24, 2015 07:44
-
-
Save hidori/e923619eec0e02c3a036 to your computer and use it in GitHub Desktop.
C# Advent Calendar 2015-12-25 #5
This file contains 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.Security.Cryptography; | |
using System.Threading; | |
namespace ConsoleApplication5 | |
{ | |
static class BetterRandom | |
{ | |
[ThreadStatic] | |
static Random Random; | |
public static Random GetRandom() | |
{ | |
if (Random == null) | |
{ | |
using (var provider = new RNGCryptoServiceProvider()) | |
{ | |
var bytes = new byte[8]; | |
provider.GetBytes(bytes); | |
var seed = BitConverter.ToInt32(bytes, 0); | |
Random = new Random(seed); | |
} | |
} | |
return Random; | |
} | |
} | |
static class Program | |
{ | |
static void Main(string[] args) | |
{ | |
const int count = 1000 * 1000; | |
var values = new int[count]; | |
int done = 0; | |
for (var i = 0; i < count; i++) | |
{ | |
ThreadPool.QueueUserWorkItem(state => | |
{ | |
var random = BetterRandom.GetRandom(); | |
var index = (int)state; | |
values[index] = random.Next(); | |
Interlocked.Add(ref done, 1); | |
}, i); | |
} | |
while (done < count) | |
{ | |
Thread.Sleep(0); | |
} | |
var zero = values.Where(value => value == 0).Count(); | |
Console.WriteLine(zero); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment