Mitigate torn writes for current time on 32-bit platforms #592
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
AfterAccessPolicyandDiscretePolicyboth store the current time in a localTimevariable to skip repeated calls to get the current time. On x86, this could result in a torn write/bad time value. Instead, use Interlocked read/write on 32bit.Results are pretty close for x64, 3x penalty for x86 (this is still incredibly cheap, it's 3x slower than reading a register). This is still at least 2x faster than calling the function to get the time.
Disassembly on X64 shows that assembly is identical for .NET6, and very similar for .NET 4.8, so the JIT is able to elide the branch and this does not introduce any overhead.
.NET 6.0.30 (6.0.3024.21525), X64 RyuJIT AVX2
.NET 6.0.30 (6.0.3024.21525), X64 RyuJIT AVX2
.NET Framework 4.8.1 (4.8.9241.0), X64 RyuJIT VectorSize=256
.NET Framework 4.8.1 (4.8.9241.0), X64 RyuJIT VectorSize=256