Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a test that shows the failure of double-checked locking in C#?

So here is my custom utility for double-checked locking: it's a static method into which you feed the criterion, the synchronisation object and the action to be performed.

public static bool RunIf(Func<bool> criterion, object syncObject, Action action)
{
    if (criterion())
        lock(syncObject)
            if (criterion())
            {
                Thread.MemoryBarrier(); 
                action();
                return true;
            }
    return false;
}

I am given to understand that, according to the C# specification, it is possible for optimisers to reorder memory allocations in such a way that, without the memory barrier, this technique can give a false positive and execute the action when it shouldn't.

In my little world, if such a failure is possible, it should also be possible to devise a test that demonstrates the failure consistently by hitting the scenario hard enough with a sufficient number of parallel test cases. I have been searching for such a test for around a year now, but so far I've drawn a blank. Can anyone show me a test that:

  1. shows the failure of this method in the absence of the memory barrier;

  2. shows its success when the test is repeated with the memory barrier restored?

like image 974
Rob Lyndon Avatar asked Jun 15 '13 19:06

Rob Lyndon


1 Answers

No, it's not possible to test non-deterministic behavior (or at least, if you do then a negative result is still inconclusive).

like image 147
Ben Voigt Avatar answered Oct 21 '22 19:10

Ben Voigt