Created
October 11, 2018 20:31
-
-
Save pamanes/c30546393fad522374004707ff3973ac to your computer and use it in GitHub Desktop.
Dan Kaminsky's DefCon RNG challenge 12 numbers at the same time in C#
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
//Created by: Alejandro Palacios ([email protected]) | |
//12 threads get a random number at the "same time" based on Dan Kaminsky's DefCon RNG challenge | |
using System; | |
using System.Text; | |
using System.Threading; | |
namespace entropy | |
{ | |
class Program | |
{ | |
static Random rand = new Random(); | |
static long time() { return DateTime.Now.Ticks; } | |
static bool flip_coin() { bool n = false; long then = time() + 1; while (time() <= then) { n = !n; } return n; } | |
static long get_fair_bit() { while (true) { bool a = flip_coin(); if (a != flip_coin()) { return (Convert.ToInt64(a)); } } } | |
static long get_random_byte() { long n = 0; int bits = 8; while (bits-- > 0) { n <<= 1; n |= get_fair_bit(); } return n; } | |
static StringBuilder val = new StringBuilder(); | |
static object _con_trans_lock = new Object(); | |
static void Main(string[] args) | |
{ | |
Thread[] threads = new Thread[12]; | |
while(true) | |
{ | |
for (int i = 0; i < threads.Length; i++) | |
threads[i] = new Thread(new ThreadStart(GetRandomNumber)); | |
for (int i = 0; i < threads.Length; i++) | |
threads[i].Start(); | |
foreach (Thread thread in threads) | |
thread.Join(); | |
Console.Out.WriteLine(val.ToString()); | |
val.Clear(); | |
} | |
} | |
static void GetRandomNumber() | |
{ | |
//8 bits:3, 16 bits: 5, 32 bits: 10 | |
string rand = get_random_byte().ToString().PadLeft(3, ' ') + " "; | |
lock (_con_trans_lock) | |
val.Append(rand); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment