简体   繁体   English

将两个线程设置为相同的cpu亲和力pthread_getaffinity_np

[英]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. 基本上,我正在尝试使主线程(main())和新创建的线程(std_thread)在同一CPU中运行。 The code prints out "Afinity ok!!!" 该代码打印出“ 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. 但是当我检查两个线程在htop工具中使用的是哪个CPU时,它们会一直随机更改,这意味着代码失败。

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 如果在代码内没有这样做的taskset则可以使用taskset命令,并且可以在创建过程时以及在运行时完成

if you want to start the process in a particular CPU, give the number as 如果要在特定的CPU中启动该进程,请将该数字指定为

taskset -c <CPUNumber> ProgramName

or dynamically you can change using PID 或动态地可以使用PID进行更改

taskset -cp <CPUNumber> PID

With pthread_getaffinity_np() , you are getting the affinity of your thread in cpuset . 使用pthread_getaffinity_np() ,您可以在cpuset中获得线程的cpuset If you check the value of this cpu set, you should notice that it spans all the cpus of your machine. 如果检查此cpu集的值,则应注意,它覆盖了计算机的所有CPU。 Indeed, by default, threads can use any cpu of the machine. 实际上,默认情况下,线程可以使用计算机的任何CPU。 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. 您实际上应该在cpuset设置一个cpu,然后设置两个线程的亲和力。 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. 您还可以使用sched_getcpu()获取正在其中运行一个线程的cpu,在cpuset设置此cpu,然后将两个线程的亲和性设置为此cpu集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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