Linux C++ thread绑定CPU

参考
加入以下语句:

    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(1, &mask); 指定该线程使用的CPU
    if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
            perror("pthread_setaffinity_np");

例子:

#include <stdio.h>
#include <math.h>
// #include <pthread.h>
#include <unistd.h>
#include <sched.h>
#include <thread>

void thread_func1()
{
    
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(1, &mask); 指定该线程使用的CPU
    if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
            perror("pthread_setaffinity_np");
        }
    ///

    int count = 0;
    while(1)
    {
        // WasteTime();
        count ++;
        usleep(100000);
    }
}
void thread_func2()
{
    int count = 0;
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(2, &mask); 
    if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
            perror("pthread_setaffinity_np");
        }
    while(1)
    {
        usleep(10000);
        // WasteTime();
        count = count*count*count/0.13414 - 2*count;
        if (count > 30000)
            count = 0;
    }
}

int main(int argc, char *argv[])
{
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(0, &mask); 
    if (sched_setaffinity(0, sizeof(mask), &mask) < 0) {
        perror("sched_setaffinity");
    }


    std::thread t1(thread_func1);
    std::thread t2(thread_func2);
    t1.join();
}
//     pthread_t my_thread;
//     if (pthread_create(&my_thread, NULL, thread_func1,
//         NULL) != 0) {
//         perror("pthread_create");
//     }
//     if (pthread_create(&my_thread, NULL, thread_func2,
//         NULL) != 0) {
//         perror("pthread_create");
//     }
//     while(1) { WasteTime(); }
//     pthread_exit(NULL);
// }


编译
g++ -o test test_thread.cpp -pthread -std=c++11
查看:

	ps -ef|grep test_thread
    top -p 6024(进程号)
    f
    光标到P,空格、s、esc
    H

对应过程:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值