Reputation: 485
I already searched for this question but none of the solutions I found helped. Maybe somebody can help me.
I have the following loop:
private static readonly Random RANDOM = new Random();
...
int[] array; // is initialized, when used. ;)
if (array.Sum() != 0)
{
int j = 0;
do {
j = RANDOM.Next(8);
} while (array[j] == 0);
}
This whole loop is in another loop which, again, is in a Parallel.Foreach
-loop.
It seems, that j
is always 0
. Most times it is not noticeable, but if array[0] == 0
, then it won't get out of the loop.
I got the suspicion that the do-while
-loop might be to fast. But also after some seconds (~30) it does not leave the loop. So the Random
does not seem to return a new or different value (even in the same thread).
I also tried this solution but with no effect.
Upvotes: 3
Views: 616
Reputation: 17139
Try this instead, since Random is not thread safe:
private static Random RANDOM = new Random();
private static object _randomLock = new object();
...
int[] array; // is initialized, when used. ;)
if (array.Sum() != 0)
{
int j = 0;
do {
lock(_randomLock)
{
j = RANDOM.Next(8);
}
} while (array[j] == 0);
}
Upvotes: 4
Reputation: 485
Thanks for the quick answers.
Matthew's answer already gave me what i needed.
I used
public static class RandomGen2
{
private static Random _global = new Random();
[ThreadStatic]
private static Random _local;
public static int Next()
{
Random inst = _local;
if (inst == null)
{
int seed;
lock (_global) seed = _global.Next();
_local = inst = new Random(seed);
}
return inst.Next();
}
}
for my solution. It works very well and quite fast.
Upvotes: 3
Reputation: 34922
Random is not threadsafe and isn't sufficiently random for parallel operations. Consider using a thread safe RNG such as RNGCryptoServiceProvider, but know that it will be a fair bit slower than Random as the algorithm to generate numbers is much more complex.
Upvotes: 2