Created
July 5, 2026 00:51
-
-
Save BradBarnich/ccd7e3811cfbe4142ff7c85ec8305c76 to your computer and use it in GitHub Desktop.
WeakReference weak publication on ARM64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections.Concurrent; | |
| using System.Runtime.CompilerServices; | |
| using System.Runtime.InteropServices; | |
| var options = Options.Parse(args); | |
| LogEnvironment(options); | |
| var replacementCache = Enumerable | |
| .Range(0, options.Slots) | |
| .Select(_ => new WeakReference<CachedReplacement?>(null)) | |
| .ToArray(); | |
| var failures = new ConcurrentQueue<Exception>(); | |
| using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(options.Seconds)); | |
| var published = 0L; | |
| var observed = 0L; | |
| var misses = 0L; | |
| var sw = System.Diagnostics.Stopwatch.StartNew(); | |
| Console.WriteLine( | |
| "Starting: writers={0}, readers={1}, slots={2}, seconds={3}, failFast={4}", | |
| options.Writers, | |
| options.Readers, | |
| options.Slots, | |
| options.Seconds, | |
| options.FailFast); | |
| var reporter = new Thread(() => | |
| { | |
| while (!cts.IsCancellationRequested && failures.IsEmpty) | |
| { | |
| Thread.Sleep(TimeSpan.FromSeconds(10)); | |
| Console.WriteLine( | |
| "progress elapsed={0:n1}s published={1:n0} observed={2:n0} misses={3:n0}", | |
| sw.Elapsed.TotalSeconds, | |
| Volatile.Read(ref published), | |
| Volatile.Read(ref observed), | |
| Volatile.Read(ref misses)); | |
| } | |
| }); | |
| reporter.Start(); | |
| var writers = Enumerable.Range(0, options.Writers).Select(writer => new Thread(() => | |
| { | |
| var iteration = 0L; | |
| var slot = writer % replacementCache.Length; | |
| while (!cts.IsCancellationRequested && failures.IsEmpty) | |
| { | |
| var replacement = CachedReplacement.Create(writer, iteration); | |
| replacementCache[slot].SetTarget(replacement); | |
| iteration++; | |
| Interlocked.Increment(ref published); | |
| slot = (slot + options.Writers) % replacementCache.Length; | |
| } | |
| })).ToArray(); | |
| var readers = Enumerable.Range(0, options.Readers).Select(reader => new Thread(() => | |
| { | |
| var iteration = 0L; | |
| var slot = reader % replacementCache.Length; | |
| while (!cts.IsCancellationRequested && failures.IsEmpty) | |
| { | |
| try | |
| { | |
| if (!replacementCache[slot].TryGetTarget(out var replacement) || | |
| replacement is null || | |
| !replacement.Pattern.Equals(CachedReplacement.ExpectedPattern, StringComparison.Ordinal)) | |
| { | |
| Interlocked.Increment(ref misses); | |
| } | |
| else | |
| { | |
| replacement.Validate(); | |
| Interlocked.Increment(ref observed); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| var failure = new ReproFailureException(reader, iteration, slot, ex); | |
| if (options.FailFast) | |
| { | |
| Environment.FailFast("WeakReference cache publication repro failed.", failure); | |
| Environment.Exit(134); | |
| } | |
| failures.Enqueue(failure); | |
| cts.Cancel(); | |
| break; | |
| } | |
| iteration++; | |
| slot = (slot + options.Readers) % replacementCache.Length; | |
| } | |
| })).ToArray(); | |
| foreach (var thread in writers.Concat(readers)) | |
| { | |
| thread.Start(); | |
| } | |
| foreach (var thread in writers.Concat(readers)) | |
| { | |
| thread.Join(); | |
| } | |
| cts.Cancel(); | |
| reporter.Join(); | |
| sw.Stop(); | |
| Console.WriteLine( | |
| "finished elapsed={0:n1}s published={1:n0} observed={2:n0} misses={3:n0}", | |
| sw.Elapsed.TotalSeconds, | |
| published, | |
| observed, | |
| misses); | |
| if (failures.TryDequeue(out var failure)) | |
| { | |
| Console.Error.WriteLine(failure); | |
| return 1; | |
| } | |
| return 0; | |
| static void LogEnvironment(Options options) | |
| { | |
| Console.WriteLine("Runtime={0}", RuntimeInformation.RuntimeIdentifier); | |
| Console.WriteLine("Framework={0}", RuntimeInformation.FrameworkDescription); | |
| Console.WriteLine("OS={0}", RuntimeInformation.OSDescription); | |
| Console.WriteLine("ProcessArchitecture={0}", RuntimeInformation.ProcessArchitecture); | |
| Console.WriteLine("OSArchitecture={0}", RuntimeInformation.OSArchitecture); | |
| Console.WriteLine("COMPlus_ReadyToRun={0}", GetRuntimeSetting("ReadyToRun")); | |
| Console.WriteLine("COMPlus_TieredCompilation={0}", GetRuntimeSetting("TieredCompilation")); | |
| Console.WriteLine("COMPlus_JitNoInline={0}", GetRuntimeSetting("JitNoInline")); | |
| Console.WriteLine("COMPlus_EnableHWIntrinsic={0}", GetRuntimeSetting("EnableHWIntrinsic")); | |
| Console.WriteLine("Options={0}", options); | |
| if (Environment.GetEnvironmentVariable("WEAKREF_REPRO_SKIP_CPUINFO") == "1" || !File.Exists("/proc/cpuinfo")) | |
| { | |
| return; | |
| } | |
| Console.WriteLine("CPU info:"); | |
| foreach (var line in File.ReadLines("/proc/cpuinfo").Where(IsInterestingCpuInfoLine).Take(32)) | |
| { | |
| Console.WriteLine(line); | |
| } | |
| } | |
| static string GetRuntimeSetting(string name) => | |
| Environment.GetEnvironmentVariable($"DOTNET_{name}") | |
| ?? Environment.GetEnvironmentVariable($"COMPlus_{name}") | |
| ?? "(unset)"; | |
| static bool IsInterestingCpuInfoLine(string line) => | |
| line.StartsWith("processor", StringComparison.OrdinalIgnoreCase) | |
| || line.StartsWith("Features", StringComparison.OrdinalIgnoreCase) | |
| || line.StartsWith("CPU implementer", StringComparison.OrdinalIgnoreCase) | |
| || line.StartsWith("CPU architecture", StringComparison.OrdinalIgnoreCase) | |
| || line.StartsWith("CPU variant", StringComparison.OrdinalIgnoreCase) | |
| || line.StartsWith("CPU part", StringComparison.OrdinalIgnoreCase) | |
| || line.StartsWith("CPU revision", StringComparison.OrdinalIgnoreCase); | |
| sealed class CachedReplacement | |
| { | |
| public const string ExpectedPattern = "badnamespace"; | |
| private const int Specials = 4; | |
| private readonly string[] _strings; | |
| private readonly int[] _rules; | |
| private readonly bool _hasBackreferences; | |
| private readonly long _iteration; | |
| private readonly int _writer; | |
| public string Pattern { get; } | |
| private CachedReplacement(string pattern, string[] strings, int[] rules, bool hasBackreferences, int writer, long iteration) | |
| { | |
| _strings = strings; | |
| _rules = rules; | |
| _hasBackreferences = hasBackreferences; | |
| _writer = writer; | |
| _iteration = iteration; | |
| // RegexReplacement assigns Pattern after building _strings and _rules. | |
| // Readers check Pattern before using the private replacement fields. | |
| Pattern = pattern; | |
| } | |
| [MethodImpl(MethodImplOptions.NoInlining)] | |
| public static CachedReplacement Create(int writer, long iteration) | |
| { | |
| var strings = new[] { ExpectedPattern, writer.ToString(), iteration.ToString() }; | |
| var rules = new[] { 0, -Specials - 1 - writer, 1, 2 }; | |
| return new CachedReplacement(ExpectedPattern, strings, rules, hasBackreferences: true, writer, iteration); | |
| } | |
| [MethodImpl(MethodImplOptions.NoInlining)] | |
| public void Validate() | |
| { | |
| if (!Pattern.Equals(ExpectedPattern, StringComparison.Ordinal)) | |
| { | |
| throw new InvalidOperationException($"Unexpected Pattern: {Pattern ?? "<null>"}"); | |
| } | |
| if (_strings is null) | |
| { | |
| throw new InvalidOperationException("_strings was null after Pattern was visible."); | |
| } | |
| if (_rules is null) | |
| { | |
| throw new InvalidOperationException("_rules was null after Pattern was visible."); | |
| } | |
| if (_strings.Length != 3 || | |
| !_strings[0].Equals(ExpectedPattern, StringComparison.Ordinal) || | |
| !_strings[1].Equals(_writer.ToString(), StringComparison.Ordinal) || | |
| !_strings[2].Equals(_iteration.ToString(), StringComparison.Ordinal)) | |
| { | |
| throw new InvalidOperationException("Replacement strings were corrupted after Pattern was visible."); | |
| } | |
| if (_rules.Length != 4 || | |
| _rules[0] != 0 || | |
| _rules[1] != -Specials - 1 - _writer || | |
| _rules[2] != 1 || | |
| _rules[3] != 2) | |
| { | |
| throw new InvalidOperationException("Replacement rules were corrupted after Pattern was visible."); | |
| } | |
| if (!_hasBackreferences) | |
| { | |
| throw new InvalidOperationException("_hasBackreferences was false after Pattern was visible."); | |
| } | |
| } | |
| } | |
| sealed record Options(int Writers, int Readers, int Slots, int Seconds, bool FailFast) | |
| { | |
| public static Options Parse(string[] args) | |
| { | |
| var writers = Environment.ProcessorCount; | |
| var readers = Environment.ProcessorCount; | |
| var slots = 16; | |
| var seconds = 600; | |
| var failFast = false; | |
| for (var i = 0; i < args.Length; i++) | |
| { | |
| switch (args[i]) | |
| { | |
| case "--writers": | |
| writers = int.Parse(args[++i]); | |
| break; | |
| case "--readers": | |
| readers = int.Parse(args[++i]); | |
| break; | |
| case "--slots": | |
| slots = int.Parse(args[++i]); | |
| break; | |
| case "--seconds": | |
| seconds = int.Parse(args[++i]); | |
| break; | |
| case "--fail-fast": | |
| failFast = true; | |
| break; | |
| default: | |
| throw new ArgumentException($"Unknown argument '{args[i]}'"); | |
| } | |
| } | |
| if (writers < 1) | |
| { | |
| throw new ArgumentOutOfRangeException(nameof(writers), writers, "Must be positive."); | |
| } | |
| if (readers < 1) | |
| { | |
| throw new ArgumentOutOfRangeException(nameof(readers), readers, "Must be positive."); | |
| } | |
| if (slots < 1) | |
| { | |
| throw new ArgumentOutOfRangeException(nameof(slots), slots, "Must be positive."); | |
| } | |
| if (seconds < 1) | |
| { | |
| throw new ArgumentOutOfRangeException(nameof(seconds), seconds, "Must be positive."); | |
| } | |
| return new Options(writers, readers, slots, seconds, failFast); | |
| } | |
| } | |
| sealed class ReproFailureException(int reader, long iterations, int slot, Exception innerException) | |
| : Exception($"Reader={reader}, Iterations={iterations}, Slot={slot}", innerException); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment