Repository navigation
Description
Description
On the file-lock (non-pthread) named mutex backend (NamedMutexProcessDataNoPThreads in src/libraries/System.Private.CoreLib/src/System/Threading/NamedMutex.Unix.cs), the TimedWaiterCount field that lives in the shared-memory file is updated with plain, non-atomic read/modify/write operations, and it is not restored when a timed wait exits through an exception.
AcquireLockCore, timed-wait (default:) branch:
_sharedData->TimedWaiterCount++;
do
{
int elapsedMilliseconds = Environment.TickCount - startTime;
if (elapsedMilliseconds >= timeoutMilliseconds)
{
_sharedData->TimedWaiterCount--;
return MutexTryAcquireLockResult.TimedOut;
}
...
Thread.Sleep(sleepMilliseconds);
} while (!SharedMemoryHelpers.TryAcquireFileLock(_sharedLockFileHandle, nonBlocking: true));
_sharedData->TimedWaiterCount--;Two problems:
- Lost updates across processes. The count is shared by every process that opened the mutex, but the only lock held around it is the process-local
_processLevelMutex, which does not serialize different processes. On x64, RyuJIT emitsinc dword ptr [rax]/dec dword ptr [rdi]with noLOCKprefix (on arm64 this is a separate load/add/store), so concurrent timed waiters in different processes can lose increments and decrements. After two lost increments, two sequential timeouts can wrap theuintto0xFFFFFFFF. - Leak on exception.
Thread.Sleepin the poll loop (andTryAcquireFileLock) can throw, e.g.ThreadInterruptedException. There is nofinally, so the count stays incremented for the life of the shared-memory file.
The pre-managed implementation (src/coreclr/pal/src/synchobj/mutex.cpp before #117788) used InterlockedIncrement/InterlockedDecrement and an RAII decrement (AutoDecTimedWaiterCount) that ran on every exit path. The managed port lost both. The old and new implementations share the same shm layout and can be active on the same file, so the update needs to be a true interlocked operation.
Consequence (from reading the code, not measured): AcquireLockCore for an infinite wait polls with Thread.Sleep(100) while TimedWaiterCount > 0, and otherwise blocks in flock. A count that is wrongly non-zero (stuck or wrapped) makes every later infinite wait on that name poll instead of block; a count that is wrongly zero removes the guard that keeps untimed waiters from starving timed waiters. It does not break mutual exclusion or ownership.
Affected platforms are those where UsePThreadMutexes is false: Linux arm/arm64, macOS/Apple platforms, FreeBSD, OpenBSD, Haiku and OpenHarmony. Linux x64 uses the pthread backend and is not affected.
Reproduction Steps
I did not have access to a stock file-lock target. I reproduced with the real System.Threading.Mutex code on Linux x64 by building main-era sources (8a1c05df905) with only the backend selector forced:
- private static bool UsePThreadMutexes =>
+ private static bool UsePThreadMutexes => false;
+ private static bool UsePThreadMutexesOriginal =>The repro below (a) creates and holds a named mutex in a driver process, (b) starts N waiter processes that, per iteration, spin to a common timestamp and call WaitOne(10) (each must time out), and (c) reads the real TimedWaiterCount (a uint at offset 8 of the runtime's own shm file, after the 8-byte shared-memory header). Every waiter performs exactly one ++ and one -- on the TimedOut path, so any non-zero count after all waiters returned is a lost update. It refuses to run if the pthread backend is active (no lockfiles/ companion file). Run on a runtime using the file-lock backend:
dotnet build -c Release
dotnet bin/Release/net10.0/repro.dll driver 3 3000 10 # 3 waiter processes, 3000 iterations, 10 ms timeout
dotnet bin/Release/net10.0/repro.dll driver 2 6000 10
dotnet bin/Release/net10.0/repro.dll interrupt # Thread.Interrupt leak
repro.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<AssemblyName>repro</AssemblyName>
</PropertyGroup>
</Project>Program.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Threading;
// Roles:
// driver <waiters> <iterations> <timeoutMs> : creates + holds the named mutex, launches <waiters> waiter processes, and
// reads the real shared counter by mapping the runtime's own shm file.
// waiter <name> <syncFile> <index> <iterations> <timeoutMs>
// interrupt : Thread.Interrupt() during a timed wait leaks +1 into the shared count.
internal static unsafe class Program
{
private const int CounterOffset = 8; // 8-byte SharedMemorySharedDataHeader, then SharedData._timedWaiterCount
private struct Control
{
public int GoIteration;
public long StartTicks;
public int Done;
public int Ready;
public int Abort;
}
private static int Main(string[] args)
{
try
{
return args[0] switch
{
"driver" => Driver(int.Parse(args[1]), int.Parse(args[2]), int.Parse(args[3])),
"interrupt" => InterruptDriver(),
"interruptwaiter" => InterruptWaiter(args[1]),
"waiter" => Waiter(args[1], args[2], int.Parse(args[3]), int.Parse(args[4]), int.Parse(args[5])),
_ => 2,
};
}
catch (Exception e)
{
Console.Error.WriteLine(e);
return 3;
}
}
// The flock backend also creates <runtime dir>/lockfiles/.../<name>; the pthread backend does not.
private static string FindShmFile(string name)
{
string? xdg = Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR");
foreach (string root in new[] { xdg is null ? "/tmp/.dotnet" : Path.Combine(xdg, ".dotnet"), "/tmp/.dotnet", "/tmp/.dotnet-uid" })
{
if (!Directory.Exists(root)) continue;
string? shm = null;
bool hasLockFile = false;
foreach (string candidate in Directory.EnumerateFiles(root, name, SearchOption.AllDirectories))
{
if (candidate.Contains("/lockfiles/")) hasLockFile = true;
else if (candidate.Contains("/shm/")) shm = candidate;
}
if (shm is null) continue;
if (!hasLockFile) throw new PlatformNotSupportedException($"{shm} has no lockfiles/ companion: pthread backend active, not the flock backend");
return shm;
}
throw new FileNotFoundException("shm file not found for " + name);
}
private static int Driver(int waiters, int iterations, int timeoutMs)
{
string name = "nm-c3-" + Guid.NewGuid().ToString("N");
string syncFile = Path.Combine(Path.GetTempPath(), name + ".sync");
using var mutex = new Mutex(initiallyOwned: true, name, out bool created);
if (!created) throw new InvalidOperationException("name collision");
string shmPath = FindShmFile(name);
Console.WriteLine($"runtime={Environment.Version} os={Environment.OSVersion} arch={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}");
Console.WriteLine($"mutex={name} shm file={shmPath} length={new FileInfo(shmPath).Length}");
using var shmFs = new FileStream(shmPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
using var shmMap = MemoryMappedFile.CreateFromFile(shmFs, null, 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: true);
using var shmView = shmMap.CreateViewAccessor(0, 4096, MemoryMappedFileAccess.ReadWrite);
byte* shmBase = null;
shmView.SafeMemoryMappedViewHandle.AcquirePointer(ref shmBase);
uint* counter = (uint*)(shmBase + shmView.PointerOffset + CounterOffset);
using var syncFs = new FileStream(syncFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
syncFs.SetLength(4096);
using var syncMap = MemoryMappedFile.CreateFromFile(syncFs, null, 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: true);
using var syncView = syncMap.CreateViewAccessor(0, 4096, MemoryMappedFileAccess.ReadWrite);
byte* syncBase = null;
syncView.SafeMemoryMappedViewHandle.AcquirePointer(ref syncBase);
Control* ctl = (Control*)(syncBase + syncView.PointerOffset);
Console.WriteLine($"initial TimedWaiterCount={*counter}");
string exe = Environment.ProcessPath!;
string dll = typeof(Program).Assembly.Location;
var procs = new List<Process>();
for (int i = 0; i < waiters; i++)
{
var psi = new ProcessStartInfo(exe) { UseShellExecute = false };
if (!Path.GetFileNameWithoutExtension(exe).Equals("repro", StringComparison.Ordinal))
{
psi.ArgumentList.Add(dll);
}
foreach (string a in new[] { "waiter", name, syncFile, i.ToString(), iterations.ToString(), timeoutMs.ToString() })
psi.ArgumentList.Add(a);
procs.Add(Process.Start(psi)!);
}
long hz = Stopwatch.Frequency;
long deadline = Stopwatch.GetTimestamp() + 30 * hz;
while (Volatile.Read(ref ctl->Ready) < waiters)
{
if (Stopwatch.GetTimestamp() > deadline) { ctl->Abort = 1; throw new TimeoutException("waiters not ready"); }
Thread.Sleep(1);
}
*counter = 0; // warm-up waits ran concurrently; start from a known value (harness-only write)
long midLost = 0, postBad = 0, wrapped = 0, maxPost = 0, minMid = waiters;
var samples = new List<string>();
for (int it = 1; it <= iterations; it++)
{
long start = Stopwatch.GetTimestamp() + hz / 500; // 2 ms lead so every waiter is spinning
Volatile.Write(ref ctl->StartTicks, start);
Volatile.Write(ref ctl->GoIteration, it);
// Two mid-wait samples (30% and 60% of the timeout). Indicative only: a late waiter also changes the count.
long midAt = start + (long)(timeoutMs * 0.3 * hz / 1000.0);
while (Stopwatch.GetTimestamp() < midAt) { }
uint mid1 = Volatile.Read(ref *counter);
long midAt2 = start + (long)(timeoutMs * 0.6 * hz / 1000.0);
while (Stopwatch.GetTimestamp() < midAt2) { }
uint mid = Volatile.Read(ref *counter);
long dl = Stopwatch.GetTimestamp() + 30 * hz;
while (Volatile.Read(ref ctl->Done) < waiters * it)
{
if (Stopwatch.GetTimestamp() > dl) { ctl->Abort = 1; throw new TimeoutException("waiters stuck at iteration " + it); }
Thread.SpinWait(50);
}
uint post = Volatile.Read(ref *counter);
if (mid != waiters && mid1 != waiters)
{
midLost++;
if (mid < minMid) minMid = mid;
if (samples.Count < 10) samples.Add($"iter {it}: mid-wait count={mid1} then {mid} (expected {waiters})");
}
if (post != 0) // definitive signal: every waiter did exactly one ++ and one --
{
postBad++;
if (post > 0x80000000u) wrapped++;
maxPost = post;
if (samples.Count < 10) samples.Add($"iter {it}: post-wait count={post} (0x{post:X8}) (expected 0)");
*counter = 0; // harness-only reset so anomalies stay independent
}
}
Volatile.Write(ref ctl->Abort, 1);
foreach (var p in procs) { if (!p.WaitForExit(30000)) p.Kill(); }
foreach (string s in samples) Console.WriteLine(s);
Console.WriteLine($"RESULT waiters={waiters} iterations={iterations} timeoutMs={timeoutMs}");
Console.WriteLine($"RESULT iterations where both mid-wait samples != waiters (indicative): {midLost}");
Console.WriteLine($"RESULT iterations with post-wait count != 0: {postBad}; of which wrapped to ~UINT32_MAX: {wrapped}; last bad value {maxPost} (0x{maxPost:X8})");
shmView.SafeMemoryMappedViewHandle.ReleasePointer();
syncView.SafeMemoryMappedViewHandle.ReleasePointer();
try { File.Delete(syncFile); } catch { }
mutex.ReleaseMutex();
return 0;
}
private static int InterruptDriver()
{
string name = "nm-c3-int-" + Guid.NewGuid().ToString("N");
using var mutex = new Mutex(initiallyOwned: true, name, out _);
string shmPath = FindShmFile(name);
using var shmFs = new FileStream(shmPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
using var shmMap = MemoryMappedFile.CreateFromFile(shmFs, null, 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: true);
using var shmView = shmMap.CreateViewAccessor(0, 4096, MemoryMappedFileAccess.ReadWrite);
byte* b = null;
shmView.SafeMemoryMappedViewHandle.AcquirePointer(ref b);
uint* counter = (uint*)(b + shmView.PointerOffset + CounterOffset);
Console.WriteLine($"runtime={Environment.Version} shm={shmPath} initial count={*counter}");
string exe = Environment.ProcessPath!;
var psi = new ProcessStartInfo(exe) { UseShellExecute = false };
if (!Path.GetFileNameWithoutExtension(exe).Equals("repro", StringComparison.Ordinal)) psi.ArgumentList.Add(typeof(Program).Assembly.Location);
psi.ArgumentList.Add("interruptwaiter");
psi.ArgumentList.Add(name);
using var child = Process.Start(psi)!;
child.WaitForExit();
Console.WriteLine($"after the interrupted wait returned (exception): count={Volatile.Read(ref *counter)} (expected 0)");
shmView.SafeMemoryMappedViewHandle.ReleasePointer();
mutex.ReleaseMutex();
return 0;
}
private static int InterruptWaiter(string name)
{
using var mutex = new Mutex(initiallyOwned: false, name);
Exception? caught = null;
var t = new Thread(() =>
{
try { mutex.WaitOne(30000); }
catch (Exception e) { caught = e; }
});
t.Start();
Thread.Sleep(200);
t.Interrupt();
t.Join();
Console.WriteLine("waiter thread ended with: " + (caught?.GetType().Name ?? "no exception"));
return 0;
}
private static int Waiter(string name, string syncFile, int index, int iterations, int timeoutMs)
{
using var mutex = new Mutex(initiallyOwned: false, name);
using var syncFs = new FileStream(syncFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
using var syncMap = MemoryMappedFile.CreateFromFile(syncFs, null, 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: true);
using var syncView = syncMap.CreateViewAccessor(0, 4096, MemoryMappedFileAccess.ReadWrite);
byte* syncBase = null;
syncView.SafeMemoryMappedViewHandle.AcquirePointer(ref syncBase);
Control* ctl = (Control*)(syncBase + syncView.PointerOffset);
for (int i = 0; i < 50; i++) mutex.WaitOne(1); // warm up the wait path
Interlocked.Increment(ref ctl->Ready);
for (int it = 1; it <= iterations; it++)
{
while (Volatile.Read(ref ctl->GoIteration) < it)
{
if (Volatile.Read(ref ctl->Abort) != 0) return 1;
Thread.SpinWait(20);
}
long start = Volatile.Read(ref ctl->StartTicks);
while (Stopwatch.GetTimestamp() < start) { }
bool got = mutex.WaitOne(timeoutMs);
if (got) { Console.Error.WriteLine("unexpected acquisition"); mutex.ReleaseMutex(); }
Interlocked.Increment(ref ctl->Done);
}
syncView.SafeMemoryMappedViewHandle.ReleasePointer();
return 0;
}
}Expected behavior
TimedWaiterCount is back to 0 once all timed waits have returned (by timeout, acquisition or exception), regardless of how many processes were waiting concurrently.
Actual behavior
Observed on Linux x64 with the file-lock backend forced (16 vCPUs; counts are iterations whose count was non-zero after all waiters had returned):
| Variant | Run | Non-zero count after all waits | of which wrapped to 0xFFFFFFFF |
|---|---|---|---|
Baseline 8a1c05df905 |
3 waiters × 3000 | 9 | 7 |
| Baseline | 2 waiters × 6000 | 3 | 1 |
Same, with Interlocked increments/decrements |
3 × 3000 and 2 × 6000 | 0 | 0 |
A 2-waiter failure looks like this in the real shm file: mid-wait count=1 then 1 (expected 2) (one lost increment), then post-wait count=4294967295 (0xFFFFFFFF) (expected 0).
The interrupt scenario (repro.dll interrupt) shows the leak deterministically: the waiter thread ends with ThreadInterruptedException, and the count is 1 afterwards instead of 0.
A native C harness with the same access pattern (several processes, one MAP_SHARED uint, no lock between them) loses updates with inc/dec dword ptr [mem] without a LOCK prefix, which is what RyuJIT emits for this code on x64 (DOTNET_JitDisasm=AcquireLockCore), and never with lock-prefixed operations.
Regression?
Yes, relative to the CoreCLR PAL implementation that preceded #117788, which used InterlockedIncrement/InterlockedDecrement and an RAII decrement.
Known Workarounds
None known besides avoiding timed waits from multiple processes on the same file-lock-backed named mutex.
Configuration
- Reproduced on Linux 6.18 x86_64,
main-era sources at8a1c05df905, file-lock backend forced via the patch above. I did not test on a stock Linux arm/arm64 or macOS build. - Hit rate is low (roughly 0.05–0.7% of iterations here) and depends on tight alignment of the waiters, so real-world frequency is unknown. The performance/starvation effect described above is from reading the code and is not measured.
Other information
The open PR #136737 changes this file but does not touch these statements or test timed waits on the file-lock backend.
A fix (atomic increment/decrement plus try/finally) with a regression test for the interrupt leak is coming in a follow-up PR.
Note
This issue was drafted with the help of GitHub Copilot (an AI assistant).
Activity
dotnet-policy-service commentedon Nov 9, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @VSadov
See info in area-owners.md if you want to be subscribed.
Make Unix named mutex timed waiter count atomic and exception safe (d…