简体   繁体   中英

How GetCurrentProcessorNumber() works? CPU core of a thread at runtime?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM