如何在 .NET 中将处理器关联设置为线程或任务? [英] How can I set processor affinity to a thread or a Task in .NET?

查看:21
本文介绍了如何在 .NET 中将处理器关联设置为线程或任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们能否在 C# 应用程序中设置两个线程或两个任务以不同的处理器关联执行?

我已经阅读了关于 SetThreadAffinityMask 的内容,但没有找到应该如何使用它的示例.

或者,有没有办法让 TPL(任务并行库)执行两个高优先级的线程/任务来使用 100% CPU?

解决方案

ProcessProcessThread 对象具有 ProcessorAffinity 属性IntPtr 类型,可直接操作以读取/更改最多 64 个处理器的关联:

<前><代码>使用 System.Diagnostics;...Process Proc = Process.GetCurrentProcess();long AffinityMask = (long)Proc.ProcessorAffinity;亲和掩码 &= 0x000F;//只使用前 4 个可用处理器中的任何一个Proc.ProcessorAffinity = (IntPtr)AffinityMask;ProcessThread 线程 = Proc.Threads[0];亲和掩码 = 0x0002;//只使用第二个处理器,尽管可用Thread.ProcessorAffinity = (IntPtr)AffinityMask;...

您还可以使用线程的 IdealProcessor 属性来允许调度程序优先在指定的处理器上运行线程(不保证).

是的,就是这么简单:)

参考:MSDN ProcessThread.ProcessorAffinity 属性

Can we set two threads or two tasks to execute with different processor affinity in a C# application?

I have read about SetThreadAffinityMask, but have found no example of how that should be used.

Alternatively, is there any way for TPL (Task Parallel Library) to execute two threads/Tasks with high priority to use 100% CPU?

解决方案

Process and ProcessThread objects have a ProcessorAffinity property of IntPtr type that can be directly manipulated to read/change affinity for up to 64 processors:


using System.Diagnostics;
...
  Process Proc = Process.GetCurrentProcess();
  long AffinityMask = (long)Proc.ProcessorAffinity;
  AffinityMask &= 0x000F; // use only any of the first 4 available processors
  Proc.ProcessorAffinity = (IntPtr)AffinityMask;

  ProcessThread Thread = Proc.Threads[0];
  AffinityMask = 0x0002; // use only the second processor, despite availability
  Thread.ProcessorAffinity = (IntPtr)AffinityMask;
...

You can also use the thread's IdealProcessor property to allow the scheduler to prefer running the thread on a specified processor (without guarantee).

Yes, it's that easy :)

Reference: MSDN ProcessThread.ProcessorAffinity Property

这篇关于如何在 .NET 中将处理器关联设置为线程或任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆