Created
May 17, 2014 14:06
-
-
Save hidori/553a16f81cb941066357 to your computer and use it in GitHub Desktop.
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.Threading; | |
namespace ConsoleApplication2 | |
{ | |
/// <summary> | |
/// static の悪夢 | |
/// </summary> | |
class Program | |
{ | |
static Random Random = new Random(); | |
/// <summary> | |
/// static 変数にキャッシュされた Random オブジェクトを使用して、マルチスレッドで大量の乱数を作成します。 | |
/// </summary> | |
static void Main(string[] args) | |
{ | |
// 試行回数: 実行環境のコア数やクロックなどによって調整の必要アリ。 | |
const int count = 1000000; | |
// 作成した乱数全件を格納するための int 配列 | |
var values = new int[count]; | |
// 作成完了した乱数の件数 | |
int done = 0; | |
// 乱数を作成 | |
for (var i = 0; i < count; i++) | |
{ | |
ThreadPool.QueueUserWorkItem(state => | |
{ | |
var index = (int)state; | |
values[index] = Random.Next(); | |
Interlocked.Add(ref done, 1); | |
}, i); | |
} | |
// 乱数作成の完了を待機 | |
while (done < count) | |
{ | |
Thread.Sleep(0); | |
} | |
// 作成された乱数のうち、値=0の件数を表示 | |
var zero = values.Where(value => value == 0).Count(); | |
Console.WriteLine("Nubmer of Zero: " + zero); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment