Is there a race condition problem in my code?

2

Is there a problem in race condition in the code below?

Private Shared Sub TestRandomNumberGeneration(ByVal random As Random)
    Dim failed As Boolean = False
    Parallel.For(0, 100000, Sub(i, state)
        Dim [next] As Integer = random.Next()
        If [next] = 0 Then
            Volatile.Write(failed, True)
            state.Stop()
        End If
    End Sub)
    Assert.IsFalse(failed)
End Sub
    
asked by anonymous 21.04.2014 / 23:07

1 answer

2

It depends. If the Stop method of the state object can only be called once (which is not clear in the question), then yes, there is a possibility, however small, of more than one thread calling this method. And it is possible, even without parallelism, that Assert.IsFalse(failed) fails - zero is a possible result for function random.Next() (assuming random is of type System.Random ).

If the Stop method can be called more than once, and if it is acceptable for Assert.IsFalse to fail, then there is no race condition in the code. This depends on the hypothesis you have about your code.

    
21.04.2014 / 23:17