Problem with Random and Threads in .NET.

I am having problems with the Random class in .NET. I am implementing a multi-threaded collection that works fine, except for one smaller detail. The collection is a list of passes , and those of you who are familiar with it know that for each inserted node I need to create a new height, which <= CurrentMaxHeight+1is the code that I use for this (I know that it is very inefficient, but it works, and this is my top priority now)

int randomLevel()
{
  int height = 1;

  while(rnd.NextDouble() >= 0.5 && height < MaxHeight)
    ++height;

  return height;
}

My problem is that sometimes I get only 1 from this for several thousand items in a row, which kills the performance of the skip list. The chance for 10,000 elements to generate only 1 of this method in a row seems very subtle (it happens quite sequentially).

So, I guess (guess) that the problem is with the object in Randomsome way, but I don’t know where to start digging. So I go over to stackoverflow to find out if anyone has an idea?

Edit

rnd-variable is declared in the class SkipList<T>, and it is accessed from several threads (each thread calls .Add in the collection and Add calls.randomLevel)

+5
source share
3

lock Random.

int RandomLevel()
{
    int height = 1;

    lock(rnd)
    {
        while(rnd.NextDouble >= 0.5 && height < MaxHeight) height++;
    }

    return height;
}

, Random , . , , MSDN, Random , lock.

+4

while. rnd.NextDouble().

int RandomLevel()
{
  int height = 1;
  double newRand;

  lock(rnd) { newRand = rnd.NextDouble(); }

  while(newRand >= 0.5 && height < MaxHeight)
  {
    height++;
    lock(rnd) { newRand = rnd.NextDouble(); }
  }

  return height;
}

, , , , , .

+3

, - , ( 0 1 > 0,5? , "1", , - , , , - 1, , "1". , , , .

, , ? , , , . , , , -, , .

+1
source

All Articles