如何确定线程运行的CPU?

Har*_*ald 14 c# c++ multithreading

有没有办法确定给定线程在哪个CPU上运行?最好是在C#中,但C++会这样做.

.NET Process和ProcessThread类似乎不提供此信息.

ETA澄清:

我们正在开发一个服务器应用程序,用于处理http多播流并生成多个视频编码器.这在具有12个物理内核的系统上运行,产生24个逻辑CPU(超线程).通过TaskManager和ProcessExplorer,我们验证了我们生成的进程在逻辑CPU上均匀分布.但是,我们在一个CPU上看到了很多(内核?)活动,这些活动因占用不寻常的CPU时间而产生干扰.我们正在尝试确定在此特定CPU上运行的进程/线程.TaskManager和ProcessExplorer似乎都没有提供这些信息.如果他们这样做,请解释如何获得这些信息.

否则,我们正在考虑编写自己的工具来获取此信息.这就是我们需要帮助的地方.

我们知道如何更改线程亲缘关系(我们知道无法保证线程将与任何CPU保持关联,尽管在这种特殊情况下,占用CPU的线程仍然只与一个CPU相关联),但是为了做到这一点,我们需要首先确定需要重新定位WHICH进程/线程.这是这个问题的唯一目标.

我希望这有助于澄清问题.

Dr.*_*ABT 4

MSDN来看,使用 ProcessThread.ProcessorAffinity 属性,您可以设置线程关联性,但无法获取它。默认情况下,线程没有关联性(可以在任何处理器上运行)。

using System;
using System.Diagnostics;

namespace ProcessThreadIdealProcessor
{
    class Program
    {
        static void Main(string[] args)
        {
            // Make sure there is an instance of notepad running.
            Process[] notepads = Process.GetProcessesByName("notepad");
            if (notepads.Length == 0)
                Process.Start("notepad");
            ProcessThreadCollection threads;
            //Process[] notepads;
            // Retrieve the Notepad processes.
            notepads = Process.GetProcessesByName("Notepad");
            // Get the ProcessThread collection for the first instance
            threads = notepads[0].Threads;
            // Set the properties on the first ProcessThread in the collection
            threads[0].IdealProcessor = 0;
            threads[0].ProcessorAffinity = (IntPtr)1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

同样Thread.SetProcessorAffinity做同样的事情。

  • @Harald 您是否尝试过使用第三方分析应用程序,例如 JetBrains dotTrace(强烈推荐)或 ANTS Profiler?http://www.jetbrains.com/profiler/ (2认同)