-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
I needed the Thread ID to implement some thread aware object pooling mechanism in a very high-traffic and tight hot-spot and was looking to use the Thread ID with a similar implementation to the OS GetCurrentThreadId (and inlined if possible).
mov rax,qword ptr gs:[30h]
mov eax,dword ptr [rax+48h]
ret
However, accessing that would either require me to p/Invoke (I don't have to tell how horrible that code is for a high-traffic tight hot-spot) or use Thread.CurrentThread.GetHashCode
or Thread.CurrentThread.ManagedThreadId
which need to access the thread object (plus a virtual code in the first case). I can't follow without a checked build for CoreCLR to see how deep the rabbit hole goes, but the Thread.CurrentThread
implementation certainly cannot beat a call and 3 instructions (even if not inlined).
The funny thing is that there is a tacit knowledge that getting the ID directly for thread aware code is necessary for high-performance code as showcased by:
// Helper method to get a logical thread ID for StringBuilder (for
// correctness) and for FileStream's async code path (for perf, to
// avoid creating a Thread instance).
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IntPtr InternalGetCurrentThread();
https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Threading/Thread.cs#L300
I propose to add:long System.Runtime.InteropServices.Thread.GetCurrentThreadId();
that would inline and call directly to the OS implementation as the internal services are using.