#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逻辑核心,
操作系统:中兴国产系统