cpu_set_t cpuset;
CPU_ZERO(&cpuset);
std::cout << "current cpu: " << sched_getcpu() << std::endl;
CPU_SET(sched_getcpu(), &cpuset);
if (pthread_setaffinity_np(std_thread.getNativeHandle(), sizeof(cpu_set_t), &cpuset) == 0) {
std::cout << "Afinity ok!!!" << std::endl;
} else {
std::cout << "second thread set affinity failed." << std::endl;
}
Basically i'm trying to have both the main thread(main()) and the new created thread(std_thread) to run in the same cpu. The code prints out "Afinity ok!!!" but when i check which cpu both threads are using in htop tool they randomly changes all the time which means the code failed.