在C#中为线程指定特殊的cpu [英] Specify a special cpu for a thread in C#

查看:71
本文介绍了在C#中为线程指定特殊的cpu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个线程.我想告诉其中一个在第一个cpu上运行,第二个在第二个cpu上运行,例如在一台具有两个cpu的计算机上运行.我该怎么办?

I have 2 threads. I want to tell one of them to run on first cpu and the second one on the second cpu for example in a machine with two cpu. how can I do that?

这是我的代码

UCI UCIMain = new UCI();
Thread UCIThread = new Thread(new ThreadStart(UCIMain.main));
UCIThread.Priority = ThreadPriority.BelowNormal;
UCIThread.Start();

,当然,类 UCI 具有一个名为 main 的成员函数.我想在第一个处理器中设置该线程

and for sure the class UCI has a member function named main. I want to set this thread in 1st processor for example

推荐答案

我不推荐这样做,但是如果您确实需要:可以通过利用本机Win32系统调用,特别是 SetThreadAffinityMask .您将需要执行一些 DllImport s:

I wouldn't recommend this, but if you really need to: it is possible by tapping into the native Win32 system calls, specifically SetThreadAffinityMask. You will need to do some DllImports:

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern IntPtr SetThreadAffinityMask(IntPtr hThread, IntPtr dwThreadAffinityMask);

然后在每个生成的线程中使用它们(当然,掩码使用不同的参数):

And then use the them inside each spawned thread (with a different parameter for the mask, of course):

// set affinity of current thread to the given cpuID
SetThreadAffinityMask(GetCurrentThread(), new IntPtr(1)); // CPU 0

这篇关于在C#中为线程指定特殊的cpu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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