有没有什么流畅的方法可以在运行时找出在多线程代码中运行的线程的 CPU 核心 ID?我尝试使用 GetCurrentProcessorNumber(),但它似乎没有给出各个线程正在运行的 CPU 内核 ID。我一直在使用的代码是:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
class S
{
[DllImport("kernel32.dll")]
static extern int GetCurrentProcessorNumber();
static void Main()
{
Task t1 = new Task(A, 1);
Task t2 = new Task(A, 2);
Task t3 = new Task(A, 3);
Task t4 = new Task(A, 4);
int myProcessorNum = GetCurrentProcessorNumber();
Console.WriteLine("processNo: " + myProcessorNum.ToString());
Console.WriteLine("Starting t1 " + t1.Id.ToString());
t1.Start();
Console.WriteLine("Starting t2 " + t2.Id.ToString());
t2.Start();
Console.WriteLine("Starting t3 " + t3.Id.ToString());
t3.Start();
Console.WriteLine("Starting t4 " + t4.Id.ToString());
t4.Start();
Console.ReadLine();
}
static void A(object o)
{
int temp = (int)o;
int myProcessorNum = GetCurrentProcessorNumber();
Console.WriteLine("Method A &" + "Thread Id: " + temp.ToString() + " and " + "processNo: " + myProcessorNum.ToString());
B(o);
}
static void B(object o)
{
int temp = (int)o;
int myProcessorNum = GetCurrentProcessorNumber();
Console.WriteLine("Method B &" + "Thread Id: " + temp.ToString() + " and " + "processNo: " + myProcessorNum.ToString());
}
}
如果我重新检查核心 ID,它会给出不同的数字:
static void A(object o)
{
int temp = (int)o;
int myProcessorNum = GetCurrentProcessorNumber();
Console.WriteLine("Method A &" + "Thread Id: " + temp.ToString() + " and " + "processNo: " + myProcessorNum.ToString());
myProcessorNum = GetCurrentProcessorNumber();
Console.WriteLine("Method A &" + "Thread Id: " + temp.ToString() + " and " + "processNo: " + myProcessorNum.ToString());
B(o);
}