This project has moved. For the latest updates, please go here.

Thread Safety?

Apr 15, 2011 at 1:29 AM

        protected override double DoSample()
        {
            byte[] bytes = new byte[4];
            mRandom.GetBytes(bytes);
            return BitConverter.ToUInt32(bytes, 0) * mReciprocal;
        }

In src/Numerics/Random/SystemCrypto.cs there's an option to make the instance thread safe. The above code sample is taken from the class and it is not thread safe.

System.Security.Cryptography.RandomNumberGenerator is not thread safe with respect to the instance members.

System.Security.Cryptography.RNGCryptoServiceProvider is thread safe, so this might have caused the confusion. I'm away from my IDE at the moment, otherwise I'd submit a patch. Just thought I'd point this out for now, though.

Apr 15, 2011 at 4:20 AM

Thread safety is handled in the abstract base class:

        private double ThreadSafeSample()
        {
            lock (_lock)
            {
                return DoSample();
            }
        }

Apr 15, 2011 at 4:26 AM

How about when a class inherits from SystemCryptoRandomNumberGenerator? Then when the inheriting class accesses the protected method, it's not thread safe... and the documentation or code would thus be incorrect.

I recommend a clarification in the documentation or moving the lock somewhere else.

Apr 15, 2011 at 5:02 AM

>How about when a class inherits from SystemCryptoRandomNumberGenerator?
>Then when the inheriting class accesses the protected method, it's not thread safe

True. We weren't expecting anyone to do that, that is, users would always use the base NextXXX methods. The only case I can think of is that a user wants a Next method that returns a double. In that case, we should just extend the base class to provide it. Is there any other case?

Apr 15, 2011 at 2:15 PM

Well I'm not sure, I simply noticed it was out of place heh.

On Apr 14, 2011 9:02 PM, "cuda" <notifications@codeplex.com> wrote:

From: cuda

>How about when a class inherits from SystemCryptoRandomNumberGenerator?
>Then when the inheriting class accesses the protected method, it's not thread safe

True. We weren't expecting anyone to do that, that is, users would always use the base NextXXX methods. The only case I can think of is that a user wants a Next method that returns a double. In that case, we should just extend the base class to provide it. Is there any other case?



Read the full discussion online.

To add a post to this discussion, reply to this email (mathnetnu...

Coordinator
Apr 18, 2011 at 9:48 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.