我必须让特定的核心忙碌等待。
例如,CPU中有4个内核(core_1,core_2,core_3,core_4),我需要让core_2忙于等待t nansecond,同时其他核心仍然处理他们的其他核任务而不忙着等待。
那么,有什么方法可以实现这一目标吗?
CPU的模型名称是 Intel(r)Xeon(R)CPU E5-2650 V3 @ 2.30GHz
此代码将您的当前线程绑定到特定核心。这是直到线程结束或您调用类似的东西为止。
这仅是您的操作系统允许
它在这里使用4.9.11-1-ARCH
与Intel(R) Core(TM) i5-3320M CPU
另请参见pthread_setaffinity_np
#include <pthread.h>
#include <iostream>
#define handle_error(msg)
do { std::cerr << msg << std::endl; exit(-1); } while (0)
void bindToSingleCore(int core)
{
pthread_t thread = pthread_self();
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core, &cpuset);
//bind this thread to one core
int s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
if (s != 0)
{
handle_error("Cannot write cpuset");
}
}
int main()
{
bindToSingleCore(1); //replace with your core
//(0==first core, 1==second, ...)
unsigned int j;
for(unsigned int i=0; i<-1; i++)
{
j+=i;
//usleep(100); //when uncommented core is not at 100% anymore..
}
}
编译并以这样的方式运行:
g++ prog.cpp -pthread && ./a.out
打开您喜欢的过程 - 监视您的核心。应该在100%加载。