c# - Random generates number 1 more than 90% of times in parallel -


this question has answer here:

consider following program:

public class program {      private static random _rnd = new random();      private static readonly int iterations = 5000000;      private static readonly int random_max = 101;       public static void main(string[] args)      {           concurrentdictionary<int,int> dic = new concurrentdictionary<int,int>();            parallel.for(0, iterations, _ => dic.addorupdate(_rnd.next(1, random_max), 1, (k, v) => v + 1));            foreach(var kv in dic)              console.writeline("{0} -> {1:0.00}%", kv.key, ((double)kv.value / iterations) * 100);      } } 

this print following output:

(note output vary on each execution)

> 1 -> 97,38% > 2 -> 0,03% > 3 -> 0,03% > 4 -> 0,03% ... > 99 -> 0,03% > 100 -> 0,03% 

why number 1 generated such frequency?

random not thread safe.

next nothing special @ ensure thread safety.

don't use random this. , don't consider using thread local storage duration either, else mess generator's statistical properties: must use 1 random instance. 1 approach use lock(_global) , draw number in locked region.

i think what's happening here first thread reach generator gets random numbers generated correctly, , subsequent threads receive 0 each drawing. "parallelisation" thread pool of 32 threads, ratios cite above approximately attainted; assuming results 31 threads placed in first bucket.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -