Skip to content

Commit 3f46bf2

Browse files
committed
Name native threads before start on macOS
1 parent 8b7cd7b commit 3f46bf2

File tree

1 file changed

+27
-0
lines changed
  • src/libraries/System.Private.CoreLib/src/System/Threading

1 file changed

+27
-0
lines changed

src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs

+27
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ public sealed partial class Thread : CriticalFinalizerObject
2424
// State associated with starting new thread
2525
private sealed class StartHelper
2626
{
27+
#if TARGET_OSX
28+
// On other platforms, when the underlying native thread is created,
29+
// the thread name is set to the name of the managed thread by another thread.
30+
// However, on OS X, only the thread itself can set its name.
31+
// The thread reference here allows the native thread to set its name before the actual work starts.
32+
// See https://github.com/dotnet/runtime/issues/106464.
33+
internal Thread? _thread;
34+
#endif
2735
internal int _maxStackSize;
2836
internal Delegate _start;
2937
internal object? _startArg;
@@ -72,6 +80,13 @@ private void RunWorker()
7280

7381
try
7482
{
83+
#if TARGET_OSX
84+
if (_thread != null && !string.IsNullOrEmpty(_thread.Name))
85+
{
86+
// Name the underlying native thread to match the managed thread name.
87+
_thread.ThreadNameChanged(_thread.Name);
88+
}
89+
#endif
7590
if (start is ThreadStart threadStart)
7691
{
7792
threadStart();
@@ -121,6 +136,9 @@ public Thread(ThreadStart start)
121136
ArgumentNullException.ThrowIfNull(start);
122137

123138
_startHelper = new StartHelper(start);
139+
#if TARGET_OSX
140+
_startHelper._thread = this;
141+
#endif
124142

125143
Initialize();
126144
}
@@ -132,6 +150,9 @@ public Thread(ThreadStart start, int maxStackSize)
132150
ArgumentOutOfRangeException.ThrowIfNegative(maxStackSize);
133151

134152
_startHelper = new StartHelper(start) { _maxStackSize = maxStackSize };
153+
#if TARGET_OSX
154+
_startHelper._thread = this;
155+
#endif
135156

136157
Initialize();
137158
}
@@ -141,6 +162,9 @@ public Thread(ParameterizedThreadStart start)
141162
ArgumentNullException.ThrowIfNull(start);
142163

143164
_startHelper = new StartHelper(start);
165+
#if TARGET_OSX
166+
_startHelper._thread = this;
167+
#endif
144168

145169
Initialize();
146170
}
@@ -152,6 +176,9 @@ public Thread(ParameterizedThreadStart start, int maxStackSize)
152176
ArgumentOutOfRangeException.ThrowIfNegative(maxStackSize);
153177

154178
_startHelper = new StartHelper(start) { _maxStackSize = maxStackSize };
179+
#if TARGET_OSX
180+
_startHelper._thread = this;
181+
#endif
155182

156183
Initialize();
157184
}

0 commit comments

Comments
 (0)