设置线程的亲缘性(指定其所运行的CPU核心)
#include <stdio.h> #include <windows.h> #include <process.h> #include <time.h> unsigned int _stdcall thread_proc(void* arg) { double x = 100.0; int r = 0; srand((unsigned)time(0) ); while(1) { r = rand();//模拟运算 x/=r; } return 0; } int main() { SYSTEM_INFO s_info={0}; DWORD cpu_count = 0; size_t i=0; HANDLE* hThread; GetSystemInfo(&s_info); //取系统CPU个数 cpu_count = s_info.dwNumberOfProcessors; //根据CPU个数创建相应数量的线程 hThread = calloc(cpu_count,sizeof(HANDLE) ); for(i=0;i<cpu_count;i++) { //创建初始状态为挂起 hThread[i] = (HANDLE)_beginthreadex(NULL,0,thread_proc,NULL,CREATE_SUSPENDED,NULL); /* *00000001:CPU0 *00000010:CPU1 *00000100:CPU2 *00001000:CPU3 **/ SetThreadAffinityMask(hThread[i], 1<<i);//CPU掩码 ResumeThread(hThread[i]);//唤醒 } printf("打开任务管理器查看...\n"); for(i=0; i<cpu_count;i++) { WaitForSingleObject(hThread[i],INFINITE); } free(hThread); return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。