Skip to content

Instantly share code, notes, and snippets.

@hidori
Created December 24, 2015 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hidori/e923619eec0e02c3a036 to your computer and use it in GitHub Desktop.
Save hidori/e923619eec0e02c3a036 to your computer and use it in GitHub Desktop.
C# Advent Calendar 2015-12-25 #5
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