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:
shows the failure of this method in the absence of the memory barrier;
shows its success when the test is repeated with the memory barrier restored?
No, it's not possible to test non-deterministic behavior (or at least, if you do then a negative result is still inconclusive).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With