This code will bind your current thread to the specific core.
This is until the thread ends or you call something similar.
This is only if your OS allows that
It works here using 4.9.11-1-ARCH
with a Intel(R) Core(TM) i5-3320M CPU
See also 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..
}
}
Compile and run with something like this:
g++ prog.cpp -pthread && ./a.out
Open your favorite process- monitor and watch your core. It should be at 100% load.