2

有没有什么流畅的方法可以在运行时找出在多线程代码中运行的线程的 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);
}
4

1 回答 1

0

如果你想要相同的cpu核心,你需要影响一个(或多个)!

http://omegacoder.com/?p=94

[DllImport("kernel32.dll")]

static extern IntPtr GetCurrentThread();

[DllImport("kernel32.dll")]

static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

在你的编:

SetThreadAffinityMask(GetCurrentThread(), new IntPtr([nb of your cpu you want]));

它工作我在我的应用程序上这样做

于 2015-08-11T17:33:01.210 回答