如何将线程/进程在一个/多个CPU核上运行
设置线程/进程与CPU的亲缘性,就是将线程/进程与CPU核进行绑定起来。
实现方法:
设置线程与指定cpu核绑定:SetThreadAffinityMask(GetCurrentThread(),mask);
设置进程与指定cpu核绑定:SetProcessAffinityMask(GetCurrentProcess(),mask);
参数说明:mask是CPU序号的或运算值:1(00000001)表示只运行在CPU第一个核上,2(00000010)表示只运行在CPU第二个核上,3(00000011)表示运行在CPU第一和第二个核上,4(00000100)表示只运行在CPU第三个核上,以此类推设置绑定对应的CPU核。
#include <iostream>
#include <Windows.h>
#include <thread>
using namespace std;
void t();
void t1(int cpu)
{
int a = 0, b = 0;
SetThreadAffinityMask(GetCurrentThread(), cpu);
int cpu_num = GetCurrentThreadNumber();
cout << cpu_num;
while (true)
{
}
}
int main() {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
printf("cpu num is %d\n", sysInfo.dwNumberOfProcessors);
std::thread fun1(t1,0x08);
std::thread fun2(t1, 0x04);
std::thread fun3(t1, 0x02);
system("pause");
return 0;
}
任务管理器查看运行情况:
![cpu使用情况](https://img-blog.csdnimg.cn/ff0df89ffbe840629020e673b940f2b2.png#pic_center)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)