绑定线程到指定cpu,CPU占用率像海波浪一样

本文介绍了一个使用C++实现的多线程应用案例,该程序通过设置线程的CPU亲和性并模拟负载均衡,使得每个线程在指定的CPU核心上运行,同时通过计算空闲和繁忙时间来模拟负载,旨在优化多核CPU上的任务调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#include <stdbool.h>
#include <unistd.h>
#include <stdio.h>
#include <sched.h>
#include <thread>
#define  N  50
#define PI 3.1415926
 
int threadName(int num,int sleepnum)
{
    sleep(sleepnum);
printf("CPUSET%d\n",num);
cpu_set_t  mask;
CPU_ZERO(&mask);
CPU_SET(num, &mask);
sched_setaffinity(0, sizeof(mask), &mask);

 
    int T = 10000;   // 10s
    int i;
    double busy[N], idle[N];
    double interval = (double)T / N ; //ms 
 
//算出每个interval的空闲时间和繁忙时间
    for(i = 0; i < N; i ++)
    {
        busy[i] = ((sin(2 * PI * i / N)/2 + 0.5) * 50 + 25 )/100 * interval;
        idle[i] =  interval - busy[i];
        //printf("%d %.2lf %.2lf\n", i, busy[i], idle[i]);
    }
 
    int j = 0;
    struct timeval  start_timeval;
    struct timeval  cur_timeval; 
     
    while (true)
    {
        gettimeofday(&start_timeval, NULL); 
        double last_ms = (double)start_timeval.tv_sec * 1000 + start_timeval.tv_usec/1000 ;
        while (true)
        {
            gettimeofday(&cur_timeval, NULL);
            double cur_ms = (double)cur_timeval.tv_sec * 1000 + cur_timeval.tv_usec/1000 ;
            if (cur_ms - last_ms >= busy[j])
                break;
        }
 
        usleep(idle[j] * 1000);
        j = (j + 1) % N;
    }
 
    exit(1);
}


int main()
{
    std::thread t1(threadName,0,0);
    std::thread t2(threadName,1,1);
    std::thread t3(threadName,2,2);
    std::thread t4(threadName,3,3);
    std::thread t5(threadName,4,4);
    std::thread t6(threadName,5,5);
    std::thread t7(threadName,6,6);
    std::thread t8(threadName,7,7);
    std::thread t9(threadName,8,8);
    std::thread t10(threadName,9,9);
    std::thread t11(threadName,10,10);
    std::thread t12(threadName,11,11);


    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    t6.join();
    t7.join();
    t8.join();
    t9.join();
    t10.join();
    t11.join();
    t12.join();

}

CPU是i7-8700,12逻辑核心,
操作系统:中兴国产系统
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值