gpt4 book ai didi

c - 多线程 C 程序中的共享字段是否大量使用 CPU?

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:25 24 4
gpt4 key购买 nike

我正在编写一个使用一定百分比 CPU 的小程序。基本策略是我会持续检查 CPU 使用率,如果使用率高于给定值,则让进程休眠。

此外,由于我使用的是 MacOS(没有像 Linux 那样的 proc/stat,在 C# 中没有 PerformanceCounter),我必须在另一个线程中执行 top 命令并从中获取 CPU 使用率。

问题是我的 CPU 使用率一直很高,即使我给出了一个很小的值作为参数。经过多次实验,这似乎是由多线程共享字段引起的。

这是我的代码(代码 1)和实验:

(code 2)一开始以为是shell命令导致使用率很高,所以在run()中注释掉死循环,只留下getCpuUsage()运行。但是,CPU 使用率几乎为零。

(code 3) 然后,我写了另一个独立于 cpuUsage 的 run() 函数,它打算使用 50% 的 CPU。它运作良好!我认为代码 1 和代码 3 之间的唯一区别是 cpuUsage 的用法。所以我想知道线程之间共享字段是否会大量使用 CPU?

代码 1

const char CPU_COMMAND[] = "top -stats cpu -l 1 -n 0| grep CPU\\ usage | cut -c 12-15";

int cpuUsage; // shared field that stores the cpu usage

// thread that continuously check CPU usage
// and store it in cpuUsage
void getCpuUsage() {
char usage[3];
FILE *out;
while (1) {
out = popen(CPU_COMMAND, "r");
if (fgets(usage, 3, out) != NULL) {
cpuUsage = atof(usage);
} else {
cpuUsage = 0;
}
pclose(out);
}
}

// keep the CPU usage under ratio
void run(int ratio) {
pthread_t id;
int ret = pthread_create(&id, NULL, (void *)getCpuUsage, NULL);
if (ret!=0) printf("thread error!");

while (1) {
// if current cpu usage is higher than ration, make it asleep
if (cpuUsage > ratio) {
usleep(10);
}
}

pthread_join(id, NULL);
}

代码 2

// keep the CPU usage under ratio
void run(int ratio) {
pthread_t id;
int ret = pthread_create(&id, NULL, (void *)getCpuUsage, NULL);
if (ret!=0) printf("thread error!");

/*while (1) {
// if current cpu usage is higher than ration, make it asleep
if (cpuUsage > ratio) {
usleep(10);
}
}*/

pthread_join(id, NULL);
}

代码 3

void run() {
const clock_t busyTime = 10;
const clock_t idleTime = busyTime;

while (1) {
clock_t startTime = clock();
while (clock() - startTime <= busyTime);
usleep(idleTime);
}
}

最佳答案

Does shared field in multithreading C program use CPU a lot?

是的,多个 CPU 上的多个线程对共享内存位置的持续读取/写入会导致缓存行在 CPU 之间不断移动(缓存反弹)。 IMO,这是在原始“并行”应用程序中可扩展性差的最重要的原因。

关于c - 多线程 C 程序中的共享字段是否大量使用 CPU?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13531658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com