How GetCurrentProcessorNumber() works? CPU core of

2019-05-27 01:26发布

问题:

Is there any smooth way to find out the CPU core id of a thread running in a multithreading code during runtime? I tried to use GetCurrentProcessorNumber(), but it seems it is not giving the CPU core id where the individual threads are running. The code I have been using is:

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());
    }
}

if I recheck the core id, it gives a different number:

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);
}

回答1:

if you want the same cpu core, you need to affect one (or more) !

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

[DllImport("kernel32.dll")]

static extern IntPtr GetCurrentThread();

[DllImport("kernel32.dll")]

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

in your prog :

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

it work i was do that on my app