我得让一个特定的核心忙着等待。
例如,cpu中有4个核(core_1,core_2,core_3,core_4),我需要让core_2忙等待t纳秒,而其他核仍然不忙等待地处理它们的任务。
那么,有什么方法可以达到这个目的吗?
cpu型号为Intel(R)Xeon(R)cpu E5-2650 v3@2.30GHz

最佳答案

此代码将把当前线程绑定到特定的核心。
直到线程结束或者你调用类似的东西。
只有在你的操作系统允许的情况下
它在这里使用4.9.11-1-ARCHIntel(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%负荷下。

关于c++ - 有什么方法可以让核心繁忙等待吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42533069/

10-11 19:32
查看更多