user492238
user492238

Reputation: 4084

Multithreading Random.NextDouble()

Which error/problems (if any) are to be expected, if NextDouble() of the same System.Random instance is called from multiple threads concurrently - without any locking ?

Upvotes: 1

Views: 562

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1064324

Since there is no guarantee of thread safety, there is no defined or sensible way of answering "nothing", "anything", and "boom" are all valid answers, and indeed it could change between versions, platforms, architecture, etc.

Have you considered making it [ThreadStatic] so each thread can have an isolated version automatically? (initialisation should probably be double-checked per thread).

Upvotes: 1

Adam Robinson
Adam Robinson

Reputation: 185703

You could corrupt the object. The Random object uses an internal array of seed values, and calling an of the Next update that array.

Don't do it.

Upvotes: 1

Dan Abramov
Dan Abramov

Reputation: 268333

In short, System.Random is not thread-safe.
For a longer answer see this awesome post which explains the issue in details.

Upvotes: 4

Sasha Goldshtein
Sasha Goldshtein

Reputation: 3519

It is difficult to tell without reverse engineering the implementation entirely. However, one thing that could happen is that the same "random" number be returned multiple times in a row (across multiple threads).

Upvotes: 0

Related Questions