Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the core/processor id of executing thread?

Tags:

c#

For example, my laptop has Intel with 2 cores and 4 logical processors. When I use the code to print info about executing thread(s), I would like to print the id of core or logical processor executing the thread. How to do it in C#

This is not a question how to get static info but dynamic info for an executing thread. As an example, this is what I use to get static info

 ManagementClass mc = new ManagementClass("win32_processor");
 ManagementObjectCollection mColl = mc.GetInstances();
 foreach (ManagementObject mObj in mColl)
 {
     PropertyDataCollection pDC = mObj.Properties;
     foreach (PropertyData pd in pDC)
        Console.WriteLine("  {0} - {1}", pd.Name, pd.Value);
 }

// Partial output

Caption - Intel64 Family 6 Model 78 Stepping 3
Description - Intel64 Family 6 Model 78 Stepping 3
DeviceID - CPU0
Name - Intel(R) Core(TM) i3 - 6006U CPU @ 2.00GHz
NumberOfCores - 2
NumberOfEnabledCore - 2
NumberOfLogicalProcessors - 4
SocketDesignation - U3E1
ThreadCount - 4   // probably threads of hyper-threading, not process threads
like image 207
Mike Portyu Avatar asked Oct 24 '25 23:10

Mike Portyu


1 Answers

You can use GetCurrentProcessorNumber

[DllImport("Kernel32.dll"), SuppressUnmanagedCodeSecurity]
public static extern int GetCurrentProcessorNumber();

static void Main(string[] args)
{
    Parallel.For (0, 10 , state => Console.WriteLine("Thread Id = {0}, CoreId = {1}",
        Thread.CurrentThread.ManagedThreadId,
        GetCurrentProcessorNumber()));
    Console.ReadKey();
}

how-to-find-which-core-your-thread-is-scheduled-on

like image 198
Jophy job Avatar answered Oct 27 '25 13:10

Jophy job