locked
Making Rand Class Thread Safe RRS feed

  • Question

  • I gather the  MicrosoftResearch.Infer.Maths.Rand class is not thread safe as according to the documentation it  says it uses a static System.Random object.  In the past I have run in to trouble with this single-random-generator-object design because if that single object is called to produce random numbers from multiple threads it begins to spit out nonsense (all zeros and the like).

    It would be nice though to have a thread safe version of the random number generators, or be able to swap out this static class for an instance variable.  To avoid writing my own, would it be possible to include the random number generators in the distributed source?  Or otherwise have an option to make them thread safe?


    • Edited by Timers1234 Wednesday, September 19, 2012 2:31 AM
    Tuesday, September 18, 2012 7:13 PM

Answers

  • The relevant fields in the Rand class are marked as ThreadStatic - i.e. they are unique for each thread. So the static Rand class should be thread safe and it has been extensively tested in calls from parallel code.

    John

    • Marked as answer by Timers1234 Friday, September 21, 2012 5:32 PM
    Thursday, September 20, 2012 10:55 AM
    Owner

All replies

  • The relevant fields in the Rand class are marked as ThreadStatic - i.e. they are unique for each thread. So the static Rand class should be thread safe and it has been extensively tested in calls from parallel code.

    John

    • Marked as answer by Timers1234 Friday, September 21, 2012 5:32 PM
    Thursday, September 20, 2012 10:55 AM
    Owner
  • Thanks for the response!  Though I certainly feel dumb for asking now.  I suspect whatever problem I was having before was because I must have been using a non-static instance of the Random class despite what I thought, and I had the same problem as described in the posts below.  Was nice to learn about the ThreadStatic attribute as well.

    http://blog.nostatic.org/2010/10/c-random-number-generator-starts.html
    http://stackoverflow.com/questions/3754170/random-number-generator-returning-zeros
    http://stackoverflow.com/questions/3196587/c-sharp-random-next-suddenly-stops-returning-random-values
    Friday, September 21, 2012 5:32 PM