Is it possible to create a test showing blocking failure with double check in C #?

So, here is my special utility for double checking: this is a static method in which you pass the criteria, the synchronization object and the action that needs 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 was given to understand that, according to the C # specification, optimizers can change the memory allocation order so that without a memory barrier this method can give a false positive result and perform an action when it should "t.

In my small world, if such a failure is possible, it should also be possible to develop a test that will demonstrate failure successively, hit hard enough with a script with enough parallel test cases. I’ve been looking for such a test for about a year, but so far I have drawn a space. Can someone show me a test that:

  • shows the failure of this method in the absence of a memory barrier;

  • shows its success when the test is repeated with the restoration of the memory barrier?

+7
source share
2 answers

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

+1
source

It is not possible to build such a test because the lock statement already creates a complete fence (ie, fence and release) for a locked instruction block. Thus, an additional Thread.MemoryBarrier() is redundant and has no effect.

So, depending on what is passed in criterion deletion, your RunIf construct is either safe or completely redundant.

What I mean is that if the delegate passed to criterion gets the return value from the mutable state, and this mutable state is not protected (directly or indirectly) by the same syncObject , this code is unsafe, and RunIf basically has no effect except surrounding instructions executed in the second call to the criterion delegate, with a complete boom.

0
source

All Articles