简体   繁体   中英

set two threads to the same cpu affinity pthread_getaffinity_np

    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.

If there is no hard reasons for doing this inside the code then you can use taskset command and can be done while process is created as well as during runtime

if you want to start the process in a particular CPU, give the number as

taskset -c <CPUNumber> ProgramName

or dynamically you can change using PID

taskset -cp <CPUNumber> PID

With pthread_getaffinity_np() , you are getting the affinity of your thread in cpuset . If you check the value of this cpu set, you should notice that it spans all the cpus of your machine. Indeed, by default, threads can use any cpu of the machine. What your code is doing is just set the affinity of your other thread to the whole machine (in other words, nothing).

What you should do is actually set a single cpu in cpuset , and then set the affinity of both your threads. You can also use sched_getcpu() to get the cpu on which one of your thread is running, set this cpu in cpuset , and then set the affinity of both your threads to this cpu set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM